淺談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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章