php中使用curl來post一段json數據
阿新 • • 發佈:2018-03-01
問題 mozilla gecko 處理 行數 agent body nts 本地
場景:在調用第三方接口時經常需要使用到curl進行數據交互,在初次使用時遇到一些小問題,記錄下來隨時查閱。
封裝curl相關方法便於使用,方法如下:
/** * @param $url * @param string $error * @param array|string $post * @param int $timeout * @param null $ref * @param string $ua * @param $contentType * @return bool|mixed */ function xcurl($url, &$error = "", $post= array(), $timeout = 5, $ref = null, $ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre", $contentType) { $ch = curl_init(); if(!empty($ref)) { curl_setopt($ch, CURLOPT_REFERER, $ref); } curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); if (false !== stripos($url, "https://")) { #https處理,不校驗相關證書 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); } if(!empty($ua)) { curl_setopt($ch, CURLOPT_USERAGENT, $ua); } if(count($post) > 0){ curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); } if (‘json‘ == $contentType) { curl_setopt($ch, CURLOPT_HTTPHEADER, array(‘Content-Type: application/json‘, ‘Content-Length: ‘ . strlen($post))); } $output = curl_exec($ch); if ($output === false) { $error = curl_error($ch); curl_close($ch); return false; } else { curl_close($ch); return $output; } }
調用如下:
<? $url = ‘localhost/php/server.php‘; $error = ‘‘; $post = [ ‘hello‘ => ‘world‘, ‘lang‘ => ‘php‘, ]; $post = json_encode($post); $result = xcurl($url,$error, $post, 5, null, ‘Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre‘, ‘json‘); var_dump($result);
本地服務接受參數時遇到了問題,無論$_POST還是$_REQUEST都無法獲取curl客戶端發送的json,所以改用file_get_contents來獲取,代碼:
print_r(file_get_contents(‘php://input‘));
最終請求curl.php獲取到結果為:
/code/php/curl.php:19:string
‘{"hello":"world","lang":"php"}‘ (length=30)
php中使用curl來post一段json數據