wp_upload_bits does not retrieve images that do not have an extension

I am using the following code to retrieve images from the web:

$get = wp_remote_get($image_file_name);
$mirror = wp_upload_bits(basename($image_file_name), '', wp_remote_retrieve_body($get));

This code works just fine with all sorts of images except when images have no extension. For example, if image file name was:

Read More
http://www.some_site.com/image_filename.jpg

then running the above code would be ok. However, the link

http://www.some_site.com/another_image_filename_but_without_extension

would give the following error:

Array
(
    [error] => Invalid file type
)

After further investigation, it looks like wp_upload_bits has the following code in it:

$wp_filetype = wp_check_filetype( $name );
if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
    return array( 'error' => __( 'Invalid file type' ) );

And it seems that it is checking if an extension actually exists, and if not, then there is an error.

So my question is how do I work around this to download images that do not have extensions?

Thanks.

Related posts

1 comment

  1. I don’t know the URL of an extension-less image to test this but I’d think that the server would have to pass a content-type header. If that is the case, you should be able to look at $get['headers']['content-type'], find out what kind of image it is, and tack the appropriate extension onto $image_file_name before sending it to wp_upload_bits.

    You’ve already retrieved the information. Take a look at var_dump($get), so the idea is to do something like this:

    $get = wp_remote_get($image_file_name);
    $ending = file_ending_parsing_function($get['headers']['content-type']);
    $mirror = wp_upload_bits(basename($image_file_name.$ending), '', wp_remote_retrieve_body($get));
    

    wp_remote_retrieve_body just grabs information already present in $get, retrieved by wp_remote_get, so you aren’t faced with downloading a file that doesn’t exist and I ran a test to confirm that the first parameter of wp_upload_bits can be anything you choose so long as the extensions match. In fact, tentative testing suggests that it just needs to have an extension. I was able to upload a .jpg and rename it to a .gif extension without manipulating the file at all.

Comments are closed.