强制下载带有外来字符的文件

时间:2014-05-09 17:25:16

标签: php character-encoding 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."/";


// And the function is :
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);

我用过:

$filename = urlencode($filename); 
$filename =  htmlentities($filename, ENT_QUOTES, "UTF-8");
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

$path = iconv('UTF-8', 'ASCII//TRANSLIT', $path) 

但没有任何效果。 我想提前感谢您,我们将非常感谢您给予的任何帮助。 纳斯。

1 个答案:

答案 0 :(得分:0)

使用它:

<?php
header('Content-Type: text/html; charset=utf-8');
?>

并确保将PHP源文件保存为utf-8。