This will work with UTF-8 filenames (say you have one in a variable called $orfilename
):
function detectUserAgent() {
if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
return "Other";
$uas = $_SERVER['HTTP_USER_AGENT'];
if (preg_match("@Opera/@", $uas))
return "Opera";
if (preg_match("@Firefox/@", $uas))
return "Firefox";
if (preg_match("@Chrome/@", $uas))
return "Chrome";
if (preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
if (((float)$matches[1]) >= 7.0)
return "IE";
}
return "Other";
}
/*
* We have 3 options:
* - For FF and Opera, which support RFC 2231, use that format.
* - For IE and Chrome, use attwithfnrawpctenclong
* (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
* - For the others, convert to ISO-8859-1, if possible
*/
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';
switch (detectUserAgent()) {
case "Opera":
case "Firefox":
$orfilename = rawurlencode($orfilename);
$format = $formatRFC2231;
break;
case "IE":
case "Chrome":
$orfilename = rawurlencode($orfilename);
$format = $formatDef;
break;
default:
if (function_exists('iconv'))
$orfilename =
@iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
$format = $formatDef;
}
header(sprintf($format, $orfilename));