我已经在命令提示符中用curl测试了这个命令,它工作了,并且做了我想做的事情。
curl -T filetoupload.tmp http://example.com -H "Accept: text/html" -H "Content-type: appliction/pdf" > filename.htm
我试着在php中表达这个(我运行php v5.5)并编写了这个代码,但是远程服务器不喜欢它,所以它显然没有做同样的事情。
$ch = curl_init("http://example.com");
$cfile = curl_file_create('filetoupload.tmp', 'application/pdf', 'filename');
$data['file'] = $cfile;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/pdf',
'Accept: text/html'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
我做错了什么?
curl -T filetoupload.tmp
上传文件为RAW post body。您的PHP代码正在发送带有标头的文件,就像您使用multipart/form-data
发布表单一样。
您需要在PHP代码中设置原始 post body。而且,看起来curl -T
使用PUT
而不是POST
。
$ch = curl_init("http://example.com");
$file = fopen('filetoupload.tmp', 'r');
curl_setopt($ch, CURLOPT_INFILE, $file);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('filetoupload.tmp'));
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/pdf',
'Accept: text/html'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
fclose($file);