如何使用ftp连接通过PHP cURL上传文件?

时间:2017-07-05 12:06:47

标签: php curl

我正在使用此脚本通过curl函数和ftp连接上传myfile。

在本地它工作正常,但在我的服务器文件中出现上传但文件大小为零。

有什么不对?谢谢。

$ch = curl_init();
$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "ftp://$user_name:$user_pass@$server/".'myfile.zip');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
curl_close ($ch);

以及如何在此脚本中上传多个文件,如:

$localfile1 = (dirname(__FILE__).'/asset/myfile1.zip');
$localfile2 = (dirname(__FILE__).'/asset/myfile2.zip');
$localfile3 = (dirname(__FILE__).'/asset/myfile3.zip');

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

要以curl上传文件,您可以使用curl_file_create。请尝试以下方法:

$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$curl_file = curl_file_create($localfile,'zip');
$params = ['file' => $curl_file];

$ch = curl_init();
$localfile = (dirname(__FILE__).'/asset/myfile.zip');
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "ftp://$user_name:$user_pass@$server/".'myfile.zip');
curl_setopt($ch, CURLOPT_UPLOAD, 1);
//curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
curl_exec ($ch);
curl_close ($ch);