wordpress PHP动态下载显示错误'内存限制,而不是下载文件[重复]

iqih9akk  于 11个月前  发布在  WordPress
关注(0)|答案(1)|浏览(122)

此问题在此处已有答案

Streaming a large file using PHP(5个答案)
28天前关闭。
我构建PHP动态下载使用此代码

<?php
include '../wp-config.php';
global $wpdb;

$allowed=false;
$user_login=wp_get_current_user();
$usersn=explode(".",str_replace("http://","",$user_login->user_url));
$usermesin=$usersn[0];

if(strtoupper(trim($usermesin))=='ALLN' || strtoupper(trim($usermesin))=='TES'){
    $allowed=true;
}

// Define the directory where your files are stored
$fileDirectory = 'downloads/';

// Get the file name from a query parameter (e.g., ?file=example.txt)
$fileName = isset($_GET['file']) ? $_GET['file'] : '';

// Check if the file exists in the directory
if (!empty($fileName) && file_exists($fileDirectory . $fileName)) {
    $filePath = $fileDirectory . $fileName;
    
    // Set the appropriate headers for the download
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . (($allowed)? basename($filePath) :'permission-denied.txt') . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filePath));
    
    // Output the file for download

    if($allowed){
        readfile($filePath);
    }else
    {
        echo"You don't have permission to download this file";
    }
    exit;
    // echo 'dapat file '.(($allowed)?'software' :'permission-denied.txt');
} else {
    // Handle file not found, e.g., display an error message
    echo 'File not found.';
}
?>

字符串
但这场演出
致命错误:/home/public_html/wp-includes/functions.php第5349行无法找到请求的URL所对应的网页
而不是downlod文件,当我运行这段代码在本地它的工作预期,因为我改变了内存限制,如何正确的方式来读取文件?

bf1o4zei

bf1o4zei1#

“已耗尽允许的内存大小”表示PHP脚本试图分配超过允许限制的内存。
在你的例子中,readfile函数导致了这个问题。当你试图读取和输出一个大文件时,可能会发生这种情况,而脚本内存不足。
要解决此问题并有效地处理大文件,您可以使用freadecho来以较小的块流式传输文件,而不是使用readfile。这将防止脚本尝试将整个文件一次加载到内存中。它以较小的块(本示例中为8KB)读取和流式传输文件,以防止耗尽内存。
下面是使用这种方法的代码的修改版本:

if ($allowed) {
    $chunkSize = 8192; // Set the chunk size here
    $file = fopen($filePath, 'rb');
    while (!feof($file)) {
        echo fread($file, $chunkSize);
        flush(); // Flush the output buffer to the browser
    }
    fclose($file);
} else {
    echo "You don't have permission to download this file";
}

字符串

相关问题