Skip to content

Instantly share code, notes, and snippets.

@azhai
Forked from shierw/cURL转发文件上传.php
Last active October 22, 2020 07:49
Show Gist options
  • Save azhai/21a5bc4c0b839f872806c8de9a8a25e7 to your computer and use it in GitHub Desktop.
Save azhai/21a5bc4c0b839f872806c8de9a8a25e7 to your computer and use it in GitHub Desktop.
cURL转发文件上传
<?php
$uploadUrl = 'http://test.com/upload.php';
// 转发从其它客户端上传的文件,上传时字段name="file",但接收方字段name="attachment"
redirect_upload($uploadUrl, 'attachment', $_FILES['file']);
/*
* 转发上传文件
*/
function redirect_upload($url, $field = 'file', $file = null)
{
if (empty($file)) {
$file = $_FILES[$field];
}
$path = realpath($file['tmp_name']);
$data = array(
$field => '@'. $path .';type='. $file['type'] .';filename=' . $file['name'],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 使用自动跳转
@curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment