Unable to get remote file name file_get_contents () and then save file

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

The problem is that the file name is not included in $urlit as www.domain.com?download=1726. This url gives me for example: myfile.exeso I want to use file_put_contents('mydir/myfile.exe');.

How can I get the file name? I tried get_headers()before downloading, but I only have the file size, date of modification and other information, the file name is missing.

+5
source share
3 answers

-. , url content-disposition, URL-. , URL ( cURL):

$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);

} 

!:)

+7

Peter222 . $http_response_header:

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);
}

: ($ http_response_header _get_contents())

$url = 'http://example.com/test.zip';
$myfile = file_get_contents($url);
$filename = get_real_filename($http_response_header,$url)
+5

file_get_contents() HTTP , -.

: file_get_contents() - (example.com/foobar.php), foobar.php, - example.com PHP . , HTML.

URL-, , . .

cURL ( ( ) URL-, , URL- ) . , , cURL.

, //- domain.com, , API .

0

All Articles