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);
}
posted @ 2024-05-13 11:03  php冉  阅读(59)  评论(0)    收藏  举报