PHP cURL表单上传文件代码,很实用。
实现代码如下:
/**
* PHP's curl extension won't let you pass in strings as multipart file upload bodies; you
* have to direct it at an existing file (either with deprecated @ syntax or the CURLFile
* type). You can use php://temp to get around this for one file, but if you want to upload
* multiple files then you've got a bit more work.
*
* This function manually constructs the multipart request body from strings and injects it
* into the supplied curl handle, with no need to touch the file system.
*
* @param $ch resource curl handle
* @param $boundary string a unique string to use for the each multipart boundary
* @param $fields string[] fields to be sent as fields rather than files, as key-value pairs
* @param $files string[] fields to be sent as files, as key-value pairs
* @return resource the curl handle with request body, and content type set
* @see http://stackoverflow.com/a/3086055/2476827 was what I used as the basis for this
**/
function buildMultiPartRequest($ch, $boundary, $fields, $files)
{
$delimiter = '-------------' . $boundary;
$data = '';
foreach ($fields as $name => $content) {
$data .= "--" . $delimiter . "\r\n"
. 'Content-Disposition: form-data; name="' . $name . "\"\r\n\r\n"
. $content . "\r\n";
}
//modify it
foreach ($files as $name => $content) {
$data .= "--" . $delimiter . "\r\n"
. 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $content['fileName'] . '"' . "\r\n\r\n"
. $content['fileContent'] . "\r\n";
}
$data .= "--" . $delimiter . "--\r\n";
curl_setopt_array($ch, [
CURLOPT_POST => TRUE,
CURLOPT_HTTPHEADER => [
'Content-Type: multipart/form-data; boundary=' . $delimiter,
'Content-Length: ' . strlen($data)
],
CURLOPT_POSTFIELDS => $data
]);
return $ch;
}
$ch = curl_init('http://httpbin.org/post');
$ch = buildMultiPartRequest($ch, uniqid(),
['key' => 'value', 'key2' => 'value2'], ['upfile' => ['fileName' => 'upload.jpg', "fileContent" => file_get_contents('file_full_path')]]);//modify it, here
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
echo curl_exec($ch);
curl_close($ch);
curl相关参数参考:http://php.net/manual/zh/function.curl-setopt.php