0

我正在尝试通过 PHP 启动文件下载。它下载,但是,文件无法打开。我的路径是正确的,因为我通过 HTML 中的图像标签预览图像进行了测试。

    $findPage = mysql_query("SELECT * FROM pages WHERE page_id = '$pageId' LIMIT 1");
    $pg = mysql_fetch_array($findPage);

    $fullPath = $pg['page_link'];
    $explode = explode(".", $fullPath);

    $ext = $explode[count($explode)-1];

    header('Content-disposition: attachment; filename="Name.'.$ext.'"');
    header('Content-type: image/'.$ext);
    readfile($fullPath);
4

1 回答 1

2

如果您尝试以下操作,您会得到什么:

$fullPath = 'https://www.google.co.uk/images/srpr/logo3w.png';

list($w,$h,$t) = getimagesize($fullPath);  
$mimetype = image_type_to_mime_type($t);
$extension = end(explode('.', $fullPath));

header('Content-disposition: attachment; filename="Name.'.$extension.'"');
header('Content-type: '.$mimetype);
readfile($fullPath);

你应该下载谷歌的标志......我在我的本地设置上下载。

*(此代码需要在您的服务器上启用 fopen_wrappers)*

如果您确实正确下载了 Google 的徽标,那么我建议您的数据库提供的数据有问题,或者 readfile 尝试访问和读取您的文件时存在权限问题。

file_exists( $fullPath ) /// will tell you if the file exists or not

is_readable( $fullPath ) /// could be useful to detect a read error

如果您没有获得 Google 的徽标,则 fopen_wrappers 在您的服务器上被禁用,或者您的代码中的其他地方发生了一些奇怪的事情。

额外说明

在哪里$pageId设置?如果它是从外部世界传递到您的脚本中的——就像通过 URL 一样——我会坚持你使用不同的方式来构建你的数据库查询。至少在将$pageId值插入查询之前,您应该对值运行某种转义函数。否则,这是一个相当安全的问题。这是因为任何有权访问您的 URL 的人显然都可以修改它,并且通过这样做他们可以直接修改您的查询。处理简单 ID 时保护数据库的最快方法是确保该值是一个数字。

$pageId = (int) $pageId;
于 2012-09-29T23:32:05.300 回答