我一直在搜索如何通过PHP中的curl上传文件...我发现你需要做的就是使用绝对路径并将“@”放在前面路径/文件名,它应该工作。不是我的情况。这是我发布文件的代码:
$url = "http://my_url/testing.php";
$partner_key = "XXXX";
$secret_key = "YYYY";
$resume_file = realpath("resumes/$newfilename");
$first_name = $_REQUEST['apply_firstname'];
$last_name = $_REQUEST['apply_lastname'];
$email = $_REQUEST['apply_email'];
$content = "partner_key=$partner_key&";
$content .= "secret_key=$secret_key&";
$content .= "resume_file=@$resume_file&";
$content .= "first_name=$first_name&";
$content .= "last_name=$last_name&";
$content .= "email=$email";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch);
curl_close($ch);
print $content . "<br>";
print $response;
这是我得到的回应。看起来整个路径在curl请求中作为值发送(即使附加了“@”),但是没有传递实际的文件信息,我可以在$ _FILES数组中获取。
Upload error!
File Info:
Array
(
)
Array
(
[partner_key] => XXXX
[secret_key] => YYYY
[resume_file] => @/var/www/html/docroot/resumes/resume-jsdkfjsdf-gmail-com-20140429015617.doc
[first_name] => john
[last_name] => johnson
[email] => jsdkfjsdf@gmail.com
)
有什么东西我不见了吗?也许我没有设定curlopt?
答案 0 :(得分:2)
问题是'@'字符不是$content
字符串中的第一个字符。此外,curl_setopt docs表示在postfields中使用'@'在PHP 5.0中已弃用
解决方案是使用CURLFile并让$content
成为数组:
$curl_file_upload = new CURLFile($resume_file);
$content = array("partner_key" => $partner_key,
"secret_key" => $secret_key,
"resume_file" => $curl_file_upload,
"first_name" => $first_name,
"last_name" => $last_name,
"email" => $email);
以后
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
希望这有帮助。
答案 1 :(得分:0)
我终于明白了!
为了使文件上传起作用,我的帖子字段必须构建为一个数组,而不仅仅是一个url字符串。
所以我改变了这个:
$content = "partner_key=$partner_key&";
$content .= "secret_key=$secret_key&";
$content .= "resume_file=@$resume_file&";
$content .= "first_name=$first_name&";
$content .= "last_name=$last_name&";
$content .= "email=$email";
对此:
$content = array(
'partner_key' => $partner_key,
'secret_key' => $secret_key,
'resume_file' => "@" . $resume_file,
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email
);
它现在工作得很好!