版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37352702/article/details/78319946
public function postFile() { $name = 'filename'; $path = './Resource/temp_pdf/'; $ext = '.pdf';
if (is_file($path . $name . $ext) && filesize($path . $name . $ext) != 0) { $url = "http://test.api.com/index.php"; $post_data = array( "foo" => "bar", //@代表此字段属于文件,接收方只需用$_FILES便可接收文件 "upload" => '@' . $path . $name . $ext, ); $res = httpRequest($url,$post_data); var_dump($res); //TODO::获取返回数据的动作 } }
/** * 请求远程地址 * * @param string $url 请求url * @param mixed $postFields 请求的数据 * @param string $referer 来源网址 * @param integer $timeOut 请求超时时间 * @param array $header 头部文件 * @return mixed 错误返回false,正确返回获取的字符串 * @author fengxu */ function httpRequest($url, $postFields = null, $referer = null, $timeOut = 300, $header = null) { if (empty($url) || !preg_match("#https?://[\w@\#$%*&=+-?;:,./]+#i", $url)) { return false; } $isPost = empty($postFields) ? false : true; $ch = curl_init(); if (is_null($header)) { $header = array( 'Pragma' => 'no-cache', 'Accept' => 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,q=0.5', 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36', ); } $headers = array(); foreach ($header as $k => $v) { $headers[] = $k . ': ' . $v; } curl_setopt($ch, CURLOPT_URL, $url); if ($isPost) { //$postFields = http_build_query($postFields); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); } curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); if ($response === false) { throw new Exception(curl_error($ch), '500'); } return $response; }