首页 > 解决方案 > PHP readfile 总是返回“网络错误”

问题描述

我想从带有readfile()函数的 URL 下载图像,但完成下载后,返回:

错误:网络错误

这是我的代码:

<?php

    $file = $_REQUEST['file'];
    $file_extension = end(explode('.', $file));
    $file_name = end(explode('/', $file));
    $filepath = str_replace('https://example.org/', '', $file);

    header('Content-Description: File Transfer');
    header('Content-Type: image/jpeg');
    header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filepath));
    flush(); // Flush system output buffer
    readfile($filepath);
    exit;

我尝试了不同的方式(fread(), fopen(), ...),但结果是一样的。

标签: phpdownloadreadfile

解决方案


这似乎符合预期,请参阅https://www.php.net/manual/en/function.readfile.php以获取以下文本:

如果启用了 fopen 包装器,则 URL 可以用作此函数的文件名。有关如何指定文件名的更多详细信息,请参阅 fopen()。请参阅支持的协议和包装器以获取有关各种包装器具有哪些功能的信息的链接、有关其使用的说明以及有关它们可能提供的任何预定义变量的信息。

根据文档,您必须启用 fopen 包装器才能使这些(面向文件的)API 在网络上工作


推荐阅读