Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get remote filename to file_get_contents() and then store file

I want to download a remote file and put it in my server directory with the same name the original has. I tried to use file_get_contents($url).

Problem is that the filename isn't included in $url, it is like: www.domain.com?download=1726. This URL give me, e.g.: myfile.exe, so I want to use file_put_contents('mydir/myfile.exe');.

How could I retrieve the filename? I tried get_headers() before downloading, but I only have file size, modification date and other information, the filename is missing.

like image 632
Peter222 Avatar asked Aug 07 '12 09:08

Peter222


2 Answers

I solved it another way. I found that if there is no content-disposition in url headers, then filename exists in URL. So, this code works with any kind of URL's (no cURL needed):

$url = "http://www.example.com/download.php?id=123";
// $url = "http://www.example.com/myfile.exe?par1=xxx";
$content = get_headers($url,1);
$content = array_change_key_case($content, CASE_LOWER);

    // by header
if ($content['content-disposition']) {
    $tmp_name = explode('=', $content['content-disposition']);
    if ($tmp_name[1]) $realfilename = trim($tmp_name[1],'";\'');
} else  

// by URL Basename
{
    $stripped_url = preg_replace('/\\?.*/', '', $url);
    $realfilename = basename($stripped_url);

} 

It works! :)

like image 62
Peter222 Avatar answered Oct 24 '22 07:10

Peter222


Based on Peter222 's code i wrote a function to get the filename. You can use the $http_response_header variable:

function get_real_filename($headers,$url)
{
    foreach($headers as $header)
    {
        if (strpos(strtolower($header),'content-disposition') !== false)
        {
            $tmp_name = explode('=', $header);
            if ($tmp_name[1]) return trim($tmp_name[1],'";\'');
        }
    }

    $stripped_url = preg_replace('/\\?.*/', '', $url);
    return basename($stripped_url);
}

Usage: ($http_response_header will be filled by file_get_contents())

$url = 'http://example.com/test.zip';
$myfile = file_get_contents($url);
$filename = get_real_filename($http_response_header,$url)
like image 27
Niksac Avatar answered Oct 24 '22 08:10

Niksac