王新阳

wangxinyang

PHP curl示例

cur进行https请求时,如果出现 curl: (35) SSL connect error
一般是发起请求的服务器ssl_version为 NSS 需要改为 openSSL

/**
 * 通过curl请求远程数据
 * @param string $url
 * @param string $request_method 默认GET
 * @param array $post_data 默认null
 * @param string $do_what http_build_query/json_encode
 * @param array $opt_array 批量设置特殊选项
 * @return FALSE | string
 */
function my_curl($url, $request_method='GET', $post_data=NULL, $do_what='', $opt_array=NULL){
	$arr_header = array();
	if($post_data){
		switch($do_what){
			case 'json_encode': //需要发送json数据时,对数组或对象进行json编码(微信开发此处不能包含中文,否则会有:不合法的请求字符,不能包含\uxxxx格式的字符)
				$post_data = json_encode($post_data);
				$arr_header[] = 'Content-length: '.strlen($post_data);
				break;
			case 'http_build_query':
				$post_data = http_build_query($post_data); //对数组或对象使用http_build_query()以提高兼容性
				$arr_header[] = 'Content-length: '.strlen($post_data);
				break;
			default:
		}
	}
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //curl_exec执行成功则返回结果(默认返回true),失败返回false
	curl_setopt($ch, CURLOPT_HEADER, false); //启用时会将头文件的信息作为数据流输出
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //连接超时时间
	if(count($arr_header))curl_setopt($ch, CURLOPT_HTTPHEADER, $arr_header);
	if(strtolower($request_method)=='post')curl_setopt($ch, CURLOPT_POST, true); //POST方式时添加
	if(strpos(strtolower($url), 'https://')===0){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //https请求时跳过cURL验证对等证书
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //https请求时跳过cURL验证域名
	}
	if($post_data)curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	if(is_array($opt_array) && count($opt_array))curl_setopt_array($ch, $opt_array);
	$output = curl_exec($ch);
//	$outinfo = curl_getinfo($ch);
	$err_no = curl_errno($ch);
	$curl_error = $err_no ?  'curl: '.curl_error($ch)." $err_no" : ''; //失败时返回当前会话最后一次错误的字符串
	curl_close($ch);
	if($err_no){
		log_message('error', $curl_error);
		return FALSE;
	}else{
		return $output;
	}
}
2015-12-30
2024-05-02 星期四 农历三月二十四