dongweizhen2009
dongweizhen2009
2011-04-09 19:30

使用PHP通过FTP实时上传文件

已采纳

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • duanfang7757 duanfang7757 10年前

    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:pass@domain.com/' . $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
    ";
    } else {
        echo "There was a problem while uploading $file
    ";
    }
    
    // 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

    点赞 评论 复制链接分享
  • douliang6563 douliang6563 10年前

    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.

    点赞 评论 复制链接分享
  • douceng7070 douceng7070 10年前

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

    PHP supports process forking, you may check pnctl.

    点赞 评论 复制链接分享

相关推荐