phpfile-uploadftp

PHP ftp_put fails


I upload XML file through FTP:

$ftp = "ftp";
$username = "username";
$pwd = "password";
$filename = $_FILES[$xyz][$abc];
$tmp = $_FILES['file']['tmp_name'];
$destination = "/Content/EnquiryXML ";

$connect = ftp_connect($ftp)or die("Unable to connect to host");
ftp_login($connect,$username,$pwd)or die("Authorization Failed");
echo "Connected!<br/>";              

if(!$filename)
{
    echo"Please select a file";
}

else
{
    ftp_put($connect,$destination.'/'.$filename,$tmp,FTP_ASCII)or die("Unable to upload");
    echo"File successfully uploaded to FTP";
}

I want to send the XML file created using DOMDocument to a FTP server but I am not able.

The ftp_put returns false.


Solution

  • Most typical cause of problems with ftp_put (or any other transfer command like ftp_get, ftp_nlist, ftp_rawlist, ftp_mlsd, ftp_fput, ftp_fget) is that PHP defaults to the active mode. And in 99% cases, one has to switch to the passive mode, to make the transfer working. Use the ftp_pasv function.

    $connect = ftp_connect($ftp) or die("Unable to connect to host");
    ftp_login($connect, $username, $pwd) or die("Authorization failed");
    // turn passive mode on
    ftp_pasv($connect, true) or die("Unable switch to passive mode");
    

    The ftp_pasv must be called after ftp_login. Calling it before has no effect.

    See also:


    Further, if your FTP server is reporting an incorrect IP address in the response to the PASV command (what is quite common, if the server is behind firewall/NAT), you might need to workaround it by using:

    ftp_set_option($connect, FTP_USEPASVADDRESS, false);
    

    See PHP FTP + Passive FTP Server Behind NAT.

    Though the right solution in this case, is to get the server fixed.