How to remove the whitespace in image name and save the new file

I am using a wordpress plugin called “Add Linked Images To Gallery” in order to save a local copy of images posted on my site. I uploaded all my files in a different hosting and I was testing this plugin in localhost to see if it does the job .

What does this plugin do :
The plugin searches for external images posted in the site , save a local copy and replace the old image address in HTML code with the new image address which is in the local.

Read More

What is the problem :

While testing the plugin in the local host , I noticed that this plugin does not correctly save images which have “white spaces” on their file names. For example :

This is an Image.png

will not display in the blog, instead this is the correct way to show it :

This%2520is%2520an%2520image.png

as you can see , the white spaces are replaced with “%2520” , I am not sure why this is happening, but the image wont show up in the blog.

I tried to modify this plugin so it automatically replaces the white space in the image file with “_” , I look at the source code and found this line:

    $content = preg_replace('/(<img[^>]* src=['"]?)('.$trans.')/', '$1'.$imgpath, $content);

which I believe is responsible for the replacing images, but when I modified it , it removed the post content and image.

Is it possible to modify this plugin, so it replace the white space in the file name first , then save a local copy, then use that local copy in the blog ?

thanks

Related posts

Leave a Reply

2 comments

  1. Use sanitize_file_name( $filename ). This function doesn’t just catch white space, it removes other special characters too:

    $special_chars = array(
        "?", "[", "]", "/", "", "=", "<", ">", ":", ";", ",", 
        "'", """, "&", "$", "#", "*", "(", ")", "|", "~", "`", 
        "!", "{", "}", chr(0)
    );
    

    Find the following line in the plugin’s code:

    $id = media_handle_sideload($file_array, $post_id, $desc);
    

    Immediately above this line add:

    $file_array['tmp_name'] = sanitize_file_name( $file_array['tmp_name'] );
    

    Caveat: I haven’t tested it.

    Make sure to rename the plugin and the plugin’s file name. Otherwise you get upgrade notices. And contact the author, ask him to implement these changes.

  2. Try replacing:

    rename($file_array['tmp_name'], $file_array['tmp_name'] . $ext);
    

    With:

    $newname = strtolower(str_replace(' ', '-', $file_array['tmp_name']));
    rename($file_array['tmp_name'], $newname . $ext);
    

    Not tested