It tries to get the real file name using three methods:
- First by checking if the server returned the name of the original file to save as (using the content-disposition http header)
- By checking the content-type header that the server returned
- If all else fails then by the filename in the requested url.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$mime_types = array( | |
"application/pdf"=>"pdf", | |
"application/octet-stream"=>"exe", | |
"application/zip"=>"zip", | |
"application/msword"=>"docx", | |
"application/msword"=>"doc", | |
"application/vnd.ms-excel"=>"xls", | |
"application/vnd.ms-powerpoint"=>"ppt", | |
"image/gif"=>"gif", | |
"image/png"=>"png", | |
"image/jpeg"=>"jpeg", | |
"image/jpg"=>"jpg", | |
"audio/mpeg"=>"mp3", | |
"audio/x-wav"=>"wav", | |
"video/mpeg"=>"mpeg", | |
"video/mpeg"=>"mpg", | |
"video/mpeg"=>"mpe", | |
"video/quicktime"=>"mov", | |
"video/x-msvideo"=>"avi", | |
"video/3gpp"=>"3gp", | |
"text/css"=>"css", | |
"application/javascript"=>"jsc", | |
"application/javascript"=>"js", | |
"text/html"=>"html" | |
); | |
//Based on http://stackoverflow.com/questions/11842721/cant-get-remote-filename-to-file-get-contents-and-then-store-file | |
function getRealFilename($headers,$url) | |
{ | |
// try to see if the server returned the file name to save | |
foreach($headers as $header) | |
{ | |
if (strpos(strtolower($header),'content-disposition') !== false) | |
{ | |
$tmp_name = explode('=', $header); | |
if (isset($tmp_name[1])) | |
{ | |
return trim($tmp_name[1],'";\''); | |
} | |
} | |
} | |
//we didn't find a file name to save-as in the header | |
//so try to guess file extension by content-type | |
foreach($headers as $header) | |
{ | |
if (strpos(strtolower($header),'content-type') !== false) | |
{ | |
$tmp_name = explode(':', $header); | |
if (isset($tmp_name[1])) | |
{ | |
$mime_type=trim($tmp_name[1]); | |
return basename(preg_replace('/\\?.*/', '', $url)).'.'.$mime_types[$mime_type]; | |
} | |
} | |
} | |
//Nothing. Just grab it from the url | |
$stripped_url = preg_replace('/\\?.*/', '', $url); | |
return basename($stripped_url); | |
} | |
//Typical usage | |
$file = file_get_contents($url); | |
$filename = getRealFilename($http_response_header,$url); | |
//now save the file | |