[英]download a file from ftp using curl and php
我正在尝试使用curl和php从ftp服务器下载文件,但我找不到任何文档可以帮助
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,"ftp://$_FTP[server]");
curl_setopt($curl, CURLOPT_FTPLISTONLY, 1);
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
我可以得到一个文件列表,但就此而言
我的猜测是你的URL指向一个目录,而不是一个文件。 您需要将CURLOPT_URL的完整URL提供给该文件。 此外,如果您想下载文件,您可能希望将其保存在某个地方。
工作范例:
$curl = curl_init();
$file = fopen("ls-lR.gz", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp://ftp.sunet.se/ls-lR.gz"); #input
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FILE, $file); #output
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
curl_exec($curl);
curl_close($curl);
fclose($file);
在curl_exec之前添加这些行:
$file = fopen("filename_to_save_to", "w"); curl_setopt($curl, CURLOPT_FILE, $file);
社区响应有微小的调整:
看来在设置CURLOPT_RETURNTRANSFER之前设置CURLOPT_FILE不起作用,可能是因为CURLOPT_FILE依赖于设置的CURLOPT_RETURNTRANSFER。
引用joeterranova对此页面的评论: http ://php.net/manual/fr/function.curl-setopt.php
请参阅CURL帮助,包括如何通过FTP连接到这里http://www.linuxformat.co.uk/wiki/index.php/PHP_-_The_Curl_library
注意:如果可以从HTTP访问该文件,那么最好只使用链接EG: http : //host.com/file.txt然后使用file_get_contents或文件函数。
然后,您可以使用http://uk.php.net/file_get_contents或任何其他方式将文件下载到您的计算机。 此选项将比使用FTP下载更好。 您可以随时使用FTP上传链接,如上面的链接所示。
在尝试了所有这些答案并且没有一个工作之后,这就是我最终的工作。
$curl = curl_init();
$fh = fopen("FILENAME.txt", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp://{$serverInfo['username']}:{$servererInfo['password']}@{$serverInfo['server']}/{$serverInfo['file']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
fwrite($fh, $result);
fclose($fh);
curl_close($curl);
$ftp_location = put your ftp adress here;
$location_login = put your login here;
$location_pwd = put your password here;
$conn_id = ftp_connect("$ftp_location");
$login_result = ftp_login($conn_id, $location_login, $location_pwd);
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
exit;
} else {
echo "Connected";
}
// get the file
// change products.csv to the file you want
$local = fopen("products.csv","w");
$result = ftp_fget($conn_id, $local,"products.csv", FTP_BINARY);
fwrite($local, $result); fclose($local);
// check upload status
if (!$result) {
echo "FTP download has failed!";
} else {
echo "Downloaded ";
}
// close the FTP stream
ftp_close($conn_id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.