php 使用PHP通过FTP上传文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4335236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uploading file through FTP using PHP
提问by Paul
I'm curious how to upload file through FTP using PHP. Let's say I have upload form and user have uploaded a file. How to transfer the file (without moving from temp directory) to some FTP host using PHP?
我很好奇如何使用 PHP 通过 FTP 上传文件。假设我有上传表单并且用户上传了一个文件。如何使用 PHP 将文件(不从临时目录移动)传输到某个 FTP 主机?
回答by Linus Kleen
Here you go:
干得好:
$ftp = ftp_connect($host,$port,$timeout);
ftp_login($ftp,$user,$pass);
$ret = ftp_nb_put($ftp, $dest_file, $source_file, FTP_BINARY, FTP_AUTORESUME);
while (FTP_MOREDATA == $ret)
{
// display progress bar, or someting
$ret = ftp_nb_continue($ftp);
}
// all done :-)
Error handling omitted for brevity.
为简洁起见省略了错误处理。
回答by Shakti Singh
Here is a code sample
这是一个代码示例
$ftp_server="";
$ftp_user_name="";
$ftp_user_pass="";
$file = "";//tobe uploaded
$remote_file = "";
// 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);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
exit;
} else {
echo "There was a problem while uploading $file\n";
exit;
}
// close the connection
ftp_close($conn_id);
回答by ethanpil
How about FTP upload via Curl? (Note: you can also use curl for SFTP, FTPS)
通过 Curl FTP 上传怎么样?(注意:你也可以使用 curl 进行 SFTP、FTPS)
<?php
$ch = curl_init();
$localfile = '/path/to/file.zip';
$remotefile = 'filename.zip';
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, 'ftp://ftp_login:[email protected]/'.$remotefile);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0) {
$error = 'File uploaded succesfully.';
} else {
$error = 'File upload error.';
}
?>
回答by Eddie Hart
Here's a function to do it for you.
这是一个可以为您完成的功能。
function uploadFTP($server, $username, $password, $local_file, $remote_file){
// connect to server
$connection = ftp_connect($server);
// login
if (@ftp_login($connection, $username, $password)){
// successfully connected
}else{
return false;
}
ftp_put($connection, $remote_file, $local_file, FTP_BINARY);
ftp_close($connection);
return true;
}
Usage:
用法:
uploadFTP("127.0.0.1", "admin", "mydog123", "C:\report.txt", "meeting/tuesday/report.txt");
回答by infugin
FTP password must be in single quote otherwise it will not accept special characters
FTP密码必须是单引号,否则不接受特殊字符
$ftp_server="";
$ftp_user_name="";
$ftp_user_pass=''; // this is the right way
$file = "";//tobe uploaded
$remote_file = "";