开发者

Download Remote File

开发者 https://www.devze.com 2022-12-28 06:58 出处:网络
I have afunction that will be passed in a link. The link is to a remote image. I thought I could just use the extension of the file in the URL to determine the type of image but some URLs won\'t have

I have a function that will be passed in a link. The link is to a remote image. I thought I could just use the extension of the file in the URL to determine the type of image but some URLs won't have extensions in the URL. They probably just push headers to the browser and therefore I do not have an extension to parse from the URL.

How can I test if the URL has an extension and if not then read the headers to determine the file type?

Am I over complicating things here? Is there an easier way to do this? I am making use of Codeigniter maybe there is something already built in to do this?

All I really want to do is download an image from a URL with the correct extension.

This is what I have so far.

function get_image($image_link){

 开发者_如何学运维   $remoteFile = $image_link;

    $ext = ''; //some URLs might not have an extension

    $file = fopen($remoteFile, "r");


    if (!$file) {

        return false;

    }else{

        $line = '';

        while (!feof ($file)) {

            $line .= fgets ($file, 4096);

        }

        $file_name = time().$ext;

        file_put_contents($file_name,  $line);

    }

    fclose($file);

}

Thanks all for any help


You never want to switch on the file extension. For example, not all ASCII text files will have ".txt", and then there's always the fun ".jpg" versus ".jpeg". Instead, switch on the Content-Type header that the web server responds with. (See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17).

Some web servers will also respect the Accept header (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1). So, if you know you only want PNG image files, then send Accept: image/png. If the server respects it, then its response will be much smaller than sending the whole unwanted file over the network connection. However, because not all web servers do this well (if at all), make sure you still switch on the Content-Type response header. It's just a bandwidth saving thing.

You could also send Accept: image/* to get any type of image.

Cheers.


You should always use the Content-Type response header to determine the type of data received. From that you can set the correct extension. URLs do not have extensions, and you should not rely on anything after a period being such.


You won't be able to read headers using fsock/fread or even file_get_contents. That's all hidden away in the background and discarded when the retrieval finishes. You'll have to use the CURL functions and set up a proper HTTP GET session using that, from which you can retrieve full details of the transfer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号