Search code examples
phpftp

how to send file to another host with ftp_pasv() via PHP?


can I send a file to another host through PHP and ftp_pasv function?

I used the following code:

$ftp_server = "ftp.domain.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$ftp_username = "USERNAME";
$ftp_userpass = "PASSWORD";
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
ftp_pasv($ftp_conn, true);
$copyBU = ftp_put($ftp_conn, $file, $file, FTP_ASCII);
ftp_close($ftp_conn);

but it copies the file corruptly and the destination zip file does not open. Is there a problem somewhere? Thank you for helping me fix it.


Solution

  • To send a file to another host using FTP in PHP with ftp_pasv(), you can follow these steps.

    <?php
    $ftp_server = 'ftp.domain.com'; 
    $ftp_user = 'USERNAME';
    $ftp_pass = 'PASSWORD';
    $remote_file = '/path/to/remote/file.txt'; // Replace with the remote file path and name
    $local_file = '/path/to/local/file.txt'; // Replace with the local file path and name
    
    // Create an FTP connection
    $ftp_conn = ftp_connect($ftp_server);
    
    if ($ftp_conn) {
        // Log in to the FTP server
        if (ftp_login($ftp_conn, $ftp_user, $ftp_pass)) {
            // Turn on passive mode (PASV)
            ftp_pasv($ftp_conn, true);
    
            // Upload the local file to the remote server
            if (ftp_put($ftp_conn, $remote_file, $local_file, FTP_BINARY)) {
                echo "File uploaded successfully.";
            } else {
                echo "Error uploading file.";
            }
    
            // Close the FTP connection
            ftp_close($ftp_conn);
        } else {
            echo "FTP login failed.";
        }
    } else {
        echo "Unable to connect to FTP server.";
    }
    ?>
    

    Please try with FTP_BINARY instead of FTP_ASCII.