【问题标题】:file_get_contents large file uploadfile_get_contents 大文件上传
【发布时间】:2014-12-15 19:53:15
【问题描述】:

我正在尝试使用 fsockopen 上传 2gb 以上的大文件。但是file_get_content出现以下错误,我无法将大文件存储在内存中。我需要分块发送数据,但不知道如何执行此操作。请问有人可以指导我吗?

致命错误:允许的内存大小为 134217728 字节已用尽(尝试分配 727826869 字节)

    $file_info =  finfo_open(FILEINFO_MIME);  
    $mime_type = finfo_file($file_info, $file_loc); 
    $file = file_get_contents($file_loc);

    $fp = fsockopen($host, 80, $errno, $errstr, 30);
    if ($fp) {
        $out = "POST /upload/".basename($url)." HTTP/1.1\r\n";
        $out .= "Host: ".$host."\r\n";
        $out .= "Accept-Language: en-US,en;q=0.8\r\n";
        $out .= "Content-Type: ".$mime_type."\r\n";
        $out .= 'Content-Length: ' . filesize($file_loc) . "\r\n";
        $out .= "Content-Disposition: attachment; filename=\"".urlencode(basename($file_loc))."\"\r\n\r\n";

        fwrite($fp, $out);
        fwrite($fp, $file);
        $response = '';
        while (!feof($fp)) {
            $response .= fgets($fp, 128);
        }
        fclose($fp);

【问题讨论】:

  • 你试过增加内存吗?
  • 我的内存有限,无法在内存中存储 2GB 及以上的文件。

标签: php


【解决方案1】:

file_get_contents 将整个文件的内容作为单个字符串变量返回。在您的情况下,这意味着它将尝试创建 2 GB 变量,这会耗尽允许的脚本内存。

尝试使用fopen 和fgets。这将允许您以更小的块处理文件。

$file_info =  finfo_open(FILEINFO_MIME);  
$mime_type = finfo_file($file_info, $file_loc); 
$fileHandle = fopen($file_loc);

$fp = fsockopen($host, 80, $errno, $errstr, 30);
if ($fp) {
    $out = "POST /upload/".basename($url)." HTTP/1.1\r\n";
    $out .= "Host: ".$host."\r\n";
    $out .= "Accept-Language: en-US,en;q=0.8\r\n";
    $out .= "Content-Type: ".$mime_type."\r\n";
    $out .= 'Content-Length: ' . filesize($file_loc) . "\r\n";
    $out .= "Content-Disposition: attachment; filename=\"".urlencode(basename($file_loc))."\"\r\n\r\n";

    fwrite($fp, $out);
    while(!feof($fileHandle)){
        fwrite($fp, fgets($fileHandle, 1024));
    }
    fclose($fileHandle);
    
    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 128);
    }
    fclose($fp);

【讨论】:

  • 正是如此,谢谢:)
【解决方案2】:

file_get_contents() 将返回指定 url/文件的内容并将该数据返回到您的变量中。这意味着如果您要下载 10gig 的文件,您将需要 PHP 中的 10gig 内存限制(加上开销)。

对于一个简单的脚本来说,这是一个可笑的内存量。您应该使用流媒体系统来下载这么多数据。例如。使用 byte-serving 以更小的块获取 url,或使用 curl 将其直接写入文件。

【讨论】:

    【解决方案3】:

    尝试使用fopen和fread分块读取文件

    function readFileChunked($filename) {
        $chunksize = 512 ; // bytes per chunk
        $handle = fopen($filename, "rb");
    
        if ($handle === false)
            return false;        
    
        while (!feof($handle)) {
            print fread($handle, $chunksize);            
            ob_flush();
            flush();
        }
    
        return  fclose($handle);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 2011-04-29
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      相关资源
      最近更新 更多