标签 PHPCURL 下的文章

在PHP中使用curl进行HTTP请求,`$usePost`设置为true可以使用post请求。

<!--?php
header("Content-type: text/html; charset=utf-8"); //设置返回内容编码
/**
 * 模拟HTTP请求
 * @param string $url
 * @param array $post_data
 */
function request($url = '',$post_data = array(),$usePost=false) {
    if (empty($url) || empty($post_data)) {
        return false;
    }
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$url);//设置网址
    curl_setopt($ch, CURLOPT_HEADER, 0);//不要返回的Header区域内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串
    curl_setopt($ch, CURLOPT_POST, $usePost);//是否以post方式提交数据
    curl_setopt($ch, CURLOPT_ENCODING, "");//设置自动解压压缩的返回内容
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//设置提交的数据
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书下同
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

$url = 'https://some.domain/somepath';
$post_data = array('param1'=>'value1','param2'=>'value2');
$res = request($url, $post_data); 
echo $res;