Skip to content

Instantly share code, notes, and snippets.

@juwencheng
Last active April 9, 2019 23:57
Show Gist options
  • Save juwencheng/04dec131533bbf50ef3681cc5daacbe3 to your computer and use it in GitHub Desktop.
Save juwencheng/04dec131533bbf50ef3681cc5daacbe3 to your computer and use it in GitHub Desktop.
PHP 使用 curl 发送 post 请求,可以自定义header和传递参数
/**
* Send a GET requst using cURL
* @param string $url to request
* @param array $get values to send
* @param array $options for cURL
* @return string
*/
function curl_get($url, array $get = NULL, array $options = array())
{
$defaults = array(
CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 4
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( ! $result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
function curl_post($url, array $params = NULL, array $headers = array())
{
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 3,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_HTTPHEADER => $headers
);
$ch = curl_init();
curl_setopt_array($ch, $defaults);
if( ! $result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
$result = curl_post("post_url", [
"key1" => "value1"
], array(
'User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 NetType/WIFI Language/en',
));
// $json 是返回的是数组
$json = json_decode($result,true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment