Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload file in chunks using PHP FTP module?

Tags:

php

ftp

plupload

I am good at to uploading file using PHP FTP functions. It is going well, if a file is not too large. But when the file size gets large size, it is failing.

So I need a code sample that connects to FTP and uploads file in chunks.

My existing code.

$ftp_server = ftp_server;
$ftp_user_name=ftp_user_name;
$ftp_user_pass=ftp_user_pass;
$file = $_FILES["file"]["tmp_name"];
$remote_file = 'uploads/'.$_GET['file_name'];
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
if ( ftp_put($conn_id, $remote_file, $file, FTP_BINARY) ) echo "Success"; else echo "Error";
ftp_close($conn_id);

Update

var uploader = new plupload.Uploader({
    runtimes : 'html5,flash,silverlight,html4',
    browse_button : 'pickfiles', // you can pass an id...
    container: document.getElementById('container'), // ... or DOM Element itself
    url : 'upload.php',
    flash_swf_url : '../js/Moxie.swf',
    silverlight_xap_url : '../js/Moxie.xap',

    filters : {
        max_file_size : '1000mb',
        mime_types: [
            {title : "Image files", extensions : "jpg,gif,png"},
            {title : "Video files", extensions : "mp4,wmv"}
        ]
    },

    init: {
        PostInit: function() {
            document.getElementById('filelist').innerHTML = '';

            document.getElementById('uploadfiles').onclick = function() {
                uploader.start();
                return false;
            };
        },

        FilesAdded: function(up, files) {
            plupload.each(files, function(file) {
                document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
            });
        },

        UploadProgress: function(up, file) {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
        },

        Error: function(up, err) {
            document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
        }
    }
});

uploader.init();

Error Error

like image 334
AWE Avatar asked Oct 18 '22 22:10

AWE


1 Answers

To upload a file in chunks to the FTP server, use the ftp_fput.

For each chunk:

  • Call ftp_fput with $startpos argument set to the length of all already uploaded chunks.
  • For $handle, use an in-memory stream with the chunk.

Alternatively, use the file_put_contents with:

  • FTP URL wrapper;
  • FILE_APPEND flag
  • $data for the chunk

Or, use the fopen (with a mode)/fwrite/fclose with FTP URL wrapper.

like image 151
Martin Prikryl Avatar answered Oct 21 '22 05:10

Martin Prikryl