强制下载瑞典字符(åäö)文件名

时间:2014-05-08 17:40:26

标签: php special-characters force-download

我使用以下代码和函数强制下载文件,如果文件名不包含Å Ä Ö等瑞典字符,则效果很好。

$file_id = $_GET['f'];

$sql =  " SELECT * ".
            " FROM attachment ".
            " WHERE attachment_id = ".$file_id." ".

            $res = mysql_query($sql);
            $row = mysql_fetch_array($res);
            $filename = $row['filename'];
            $USER_ID = $row['user_id'];
            $Directory_id = $row['directory_id'];
            $target_path = "upload/".$USER_ID."/".$Directory_id."/";


function Download($path, $speed = null)
{
    if (is_file($path) === true)
    {
        $file = @fopen($path, 'rb');
        $speed = (isset($speed) === true) ? round($speed * 1024) : 524288;

        if (is_resource($file) === true)
        {
            set_time_limit(0);
            ignore_user_abort(false);

            while (ob_get_level() > 0)
            {
                ob_end_clean();
            }

            header('Expires: 0');
            header('Pragma: public');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Content-Type: application/octet-stream');
            header('Content-Length: ' . sprintf('%u', filesize($path)));
            header('Content-Disposition: attachment; filename="' . basename($path) . '"');
            header('Content-Transfer-Encoding: binary');

            while (feof($file) !== true)
            {
                echo fread($file, $speed);

                while (ob_get_level() > 0)
                {
                    ob_end_flush();
                }

                flush();
                sleep(1);
            }

            fclose($file);
        }

        exit();
    }

    return false;

    }
Download($target_path.$filename);

我试图把它放在我的页面顶部:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

$filename = urlencode($filename); 

或者:

$filename =  htmlentities($filename, ENT_QUOTES, "UTF-8");
但仍然是同样的问题,我无法打开它们。但如果文件名保持正常的英文字符,那么它可以正常工作。

您是否有任何建议我可以为该功能添加或实施哪些内容?我们将非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

确保您的html文档中包含utf8编码 (<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>)

尝试替换

$filename = $row['filename'];

$filename = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $row['filename']);   

所以你的代码看起来像是:

$file_id = $_GET['f'];

$sql =  " SELECT * ".
            " FROM attachment ".
            " WHERE attachment_id = ".$file_id." ".

            $res = mysql_query($sql);
            $row = mysql_fetch_array($res);
            $filename = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $row['filename']);   
            $USER_ID = $row['user_id'];
            $Directory_id = $row['directory_id'];
            $target_path = "upload/".$USER_ID."/".$Directory_id."/";

但是为了它。不要使用mysql() - 函数。使用mysqli或PDO代替占位符。您的代码广泛用于SQL注入攻击。