32 mins ago
32 mins ago

Reputation: 75

Real-time file uploading through FTP using PHP

Is it possible to upload a file to the FTP server using PHP script while the same script is downloading the meant file from somewhere else? So at the time script is downloading it should upload the file in real-time.

Upvotes: 1

Views: 1451

Answers (3)

SIFE
SIFE

Reputation: 5695

PHP can deal with the ftp protocol, here is an example from the php manual.

PHP supports process forking, you may check pnctl.

Upvotes: 0

Sajid
Sajid

Reputation: 4421

Easy as cake, in theory. First, see FTP function here: http://www.php.net/manual/en/function.ftp-fput.php. Then we use FOPEN wrappers ( http://www.php.net/manual/en/wrappers.php ) to open the file we want to read, and send it over.

To modify the php.net example:

<?php

// open some file for reading
$file = 'somefile.txt';
$fp = fopen('ftp://user:[email protected]/' . $file, 'r');

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to upload $file
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
    echo "Successfully uploaded $file\n";
} else {
    echo "There was a problem while uploading $file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($fp);

?>

Oh, and you might want non-blocking sometimes: http://www.php.net/manual/en/function.ftp-nb-fput.php

Upvotes: 1

Charles
Charles

Reputation: 51411

PHP's built-in FTP extension can upload and download files in an asynchronous manner.

However it sounds like you're talking about using this as a method to transfer a file between two different FTP connections without downloading the whole thing first. I'm not sure if these functions support that. In fact, I'd expect otherwise -- chances are that the upload could reach the end of the file while the download is going, and simply assume that it's hit the end and complete itself.

There are some comments on the upload manual link that suggest that you can trick some servers into performing a direct connection using passive mode, but I'd take that with a grain of salt.

You might have some luck using the FTP stream wrappers. You could open up two FTP wrappers as file handles, then use fread to retrieve chunks of a specific size from one side and fwrite to write them to the other side. Keep in mind that you'd need to do this in a loop, so it can't be done in the background like the FTP extension's methods. It's also likely to be slow.

Upvotes: 0

Related Questions