PHP使用file_get_contents发送get和post请求

1、GET请求

function getData($url,$data = null){
    if ($data){
        $url .= '?'.http_build_query($data);
    }
    return file_get_contents($url);
}

2、POST请求

function postData($url,$data = [],$json = false){
    if($json){
        $str = 'application/json';
        $data = json_encode($data);
    }else{
        $str = 'application/x-www-form-urlencoded';
        $data = http_build_query($data);
    }
    $options[ 'http' ] = array(
        'timeout' => 10,
        'method'  => 'POST',
        'header'  => "Content-Type: $str;charset=utf-8",
        'content' => $data,
    );
    $context = stream_context_create($options);
    return file_get_contents($url, false, $context);
}
发布了31 篇原创文章 · 获赞 27 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Hjingeng/article/details/103765254