PHP动态下载显示错误'内存限制而不是下载文件

问题描述 投票:0回答:1

我使用此代码动态构建 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.';
}
?>

但是这个显示

致命错误:允许的内存大小 536870912 字节已耗尽(已尝试 分配 427106304 字节) /home/bengke28/public_html/wp-includes/functions.php 第 5349 行

当我在本地运行此代码时,它不会下载文件,而是按预期工作,因为我更改了内存限制,如何正确地读取文件?

php wordpress download memory-limit
1个回答
0
投票

“允许的内存大小耗尽”表示 PHP 脚本正在尝试分配超过允许限制的内存。

在您的情况下,

readfile
功能导致了问题。当您尝试读取和输出大文件,并且脚本内存不足来处理它时,可能会发生这种情况。

要解决此问题并有效地提供大文件,您可以使用

readfile
fread
以较小的块传输文件,而不是使用
echo
。这将阻止脚本尝试将整个文件立即加载到内存中。它以较小的块(本例中为 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";
}
© www.soinside.com 2019 - 2024. All rights reserved.