Alternative to Stream_Copy_To_Stream() php

前端 未结 1 1432
囚心锁ツ
囚心锁ツ 2021-02-09 04:51

I am working on a file sharing site right now and I\'ve run into a small problem. I am using the upload scrip uploadify which works perfectly but if the user wants i want the up

相关标签:
1条回答
  • 2021-02-09 05:35

    Do you have better results if you try reading the file in chunks like this?:

    $my_file = fopen($temp_file, 'rb');
    
    $encrypted_file_name = $target_file;
    $encrypted_file = fopen($encrypted_file_name, 'wb');
    
    stream_filter_append($encrypted_file, 'mcrypt.rijndael_128', STREAM_FILTER_WRITE, $opts);
    //stream_copy_to_stream($my_file, $encrypted_file);
    
    rewind($my_file);
    
    while (!feof($my_file)) {
        fwrite($encrypted_file, fread($my_file, 4096));
    }
    

    You might also try calling stream_set_chunk_size prior to calling stream_copy_to_stream to set the size of the buffer it uses to read from the source stream when copying to the destination.

    Hope that helps.

    EDIT: I tested with this code and when uploading a 700MB movie file, the peak memory usage of PHP is 524,288 bytes. It looks like stream_copy_to_stream will try to read the entire source file into memory unless you read it in chunks passing the length and offset arguments.

    $encrypted_file_name = $target_file;
    $encrypted_file = fopen($encrypted_file_name, 'wb');
    
    stream_filter_append($encrypted_file, 'mcrypt.rijndael_128', STREAM_FILTER_WRITE, $opts);
    
    $size = 16777216;  // buffer size of copy
    $pos  = 0;         // initial file position
    
    fseek($my_file, 0, SEEK_END);
    $length = ftell($my_file);    // get file size
    
    while ($pos < $length) {
        $writ = stream_copy_to_stream($my_file, $encrypted_file, $size, $pos);
        $pos += $writ;
    }
    
    fclose($encrypted_file);
    fclose($my_file);
    unlink($temp_file);
    
    0 讨论(0)
提交回复
热议问题