简体   繁体   中英

php upload local file to ftp server

i understand that the ftp_put method uploads a file from the local server computer to the ftp server but i have problems using it where when i try to execute a simple script like this:

 <?php
// connect and login to FTP server
$ftp_server = "ftp.example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);
$file = "localfile.txt";
// upload file
if (ftp_put($ftp_conn, "serverfile.txt", $file, FTP_ASCII))
{
echo "Successfully uploaded $file.";
}
else
{
echo "Error uploading $file.";
}

// close connection
ftp_close($ftp_conn);
?>  

the operation is successfully done except for that the file uploaded to the my ftp server is always with zero byte size!

also i tried to enable passive mode but it still uploads an empty file.

Try enabling track_errors and access $php_errormsg

ini_set('track_errors', 1);
// put operation
// if error
var_dump($php_errormsg);

I had the same issue. When I change "FTP_ASCII" to "FTP_BINARY" it solved my problem and files uploaded as expected.

I had ran into this as well. Bit late but thought I'd post my solution:

$file_name = "localfile.txt";

Get content from your existing file

$content = file_get_contents('http://www.somewhere.com/'.$file_name);

...or make temp file content

$content = "This is content";

upload file

// connect
$conn_id = ftp_connect($host);
$login = ftp_login($conn_id, $username, $password);
ftp_pasv($conn_id, true);

// create
$tmp = fopen(tempnam(sys_get_temp_dir(), $file), "w+");
fwrite($tmp, $content);
rewind($tmp);

// upload
$upload = ftp_fput($conn_id, "serverfile.txt", $tmp, FTP_ASCII);

// close
ftp_close($conn_id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM