溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PHP如何實現(xiàn)網(wǎng)絡(luò)請求

發(fā)布時間:2022-07-04 10:06:27 來源:億速云 閱讀:157 作者:iii 欄目:開發(fā)技術(shù)

這篇“PHP如何實現(xiàn)網(wǎng)絡(luò)請求”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“PHP如何實現(xiàn)網(wǎng)絡(luò)請求”文章吧。

一、分析php發(fā)送網(wǎng)網(wǎng)絡(luò)請求的方法

對于php發(fā)送網(wǎng)絡(luò)請求,我們最常用的請求就是curl,有時我們也會用到file_get_contents函數(shù)發(fā)送網(wǎng)絡(luò)請求,但file_get_contents只能完成一些間單的網(wǎng)絡(luò)請求,稍復(fù)雜的就無法完成,例如文件上傳,cookies,驗證,表單提交等,用php的curl可以使用URL的語法模擬瀏覽器來傳輸數(shù)據(jù),因為它是模擬瀏覽器,因此它同樣支持多種協(xié)議,F(xiàn)TP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP等協(xié)議都可以很好的支持,包括一些:HTTPS認證,HTTP POST方法,HTTP PUT方法,F(xiàn)TP上傳,keyberos認證,HTTP上傳,代理服務(wù)器,cookies,用戶名/密碼認證,下載文件斷點續(xù)傳,上傳文件斷點續(xù)傳,http代理服務(wù)器管道,甚至它還支持IPv6,scoket5代理服務(wù)器,通過http代理服務(wù)器上傳文件到FTP服務(wù)器等等,所以我們在開發(fā)中盡量用curl發(fā)網(wǎng)絡(luò)請求,無論是簡單還是復(fù)雜

二、file_get_contents發(fā)送網(wǎng)絡(luò)請求示例

file_get_contents(path,include_path,context,start,max_length)

PHP如何實現(xiàn)網(wǎng)絡(luò)請求

一般用file_get_contents或者fopen, file , readfile等函數(shù)讀取url的時候 會創(chuàng)建一個$http_response_header變量保存HTTP響應(yīng)的報頭,使用fopen等函數(shù)打開的數(shù)據(jù)流信息可以用stream_get_meta_data獲取

$html = file_get_contents('http://www.baidu.com');
print_r($http_response_header);
$fp = fopen('http://www.baidu.com', 'r');
print_r(stream_get_meta_data($fp));
fclose($fp);

摸擬post請求:

$url = 'http://192.168.1.1/test.php';
$data = array(
    'keyword' => 'test data',
);
$content = http_build_query($data);
$content_length = strlen($content);
$options = array(
    'http' => array(
        'method' => 'POST',
        'header' =>
        "Content-type: application/x-www-form-urlencoded\r\n" .
        "Content-length: $content_length\r\n",
        'content' => $content
    )
);
echo file_get_contents($url, false, stream_context_create($options));

三、php 用curl發(fā)送網(wǎng)絡(luò)請求

curl可以支持https認證、http post、ftp上傳、代理、cookies、簡單口令認證等等功能,使用前需要先在你的PHP環(huán)境中安裝和啟用curl模塊,這里有兩種寫法供大家參考:

<?php
function geturl($url){
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
}
 
 
function posturl($url,$data){
        $data  = json_encode($data);    
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output,true);
}
 
 
function puturl($url,$data){
    $data = json_encode($data);
    $ch = curl_init(); //初始化CURL句柄 
    curl_setopt($ch, CURLOPT_URL, $url); //設(shè)置請求的URL
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //設(shè)為TRUE把curl_exec()結(jié)果轉(zhuǎn)化為字串,而不是直接輸出 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //設(shè)置請求方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//設(shè)置提交的字符串
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output,true);
}
 
function delurl($url,$data){
    $data  = json_encode($data);
    $ch = curl_init();
    curl_setopt ($ch,CURLOPT_URL,$put_url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");   
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    $output = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($output,true);
}
 
function patchurl($url,$data){
    $data  = json_encode($data);
    $ch = curl_init();
    curl_setopt ($ch,CURLOPT_URL,$url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PATCH");  
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);     //20170611修改接口,用/id的方式傳遞,直接寫在url中了
    $output = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($output);
    return $output;
}
?>

一個函數(shù)片時各種請求:

function sendCurl($url, $data = null,$method='POST')
{
    $method=strtoupper($method);
    $start_wdmcurl_time = microtime(true);
 
    $header = array(' application/x-www-form-urlencoded');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    // https 請求
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
    {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if($method=='GET'){
        if($data && is_array($data) && count($data)>0 ){
            $url.="?".http_build_query($data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
    }elseif($method=='POST'){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        if (is_array($data) && count($data)>0)
        {
            curl_setopt($ch, CURLOPT_POST, true);
            $isPostMultipart = false;
            foreach ($data as $k => $v)
            {
                if ('@' == substr($v, 0, 1))
                {
                    $isPostMultipart = true;
                    break;
                }
            }
            unset($k, $v);
            if ($isPostMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            }
        }
    }elseif(in_array($method,['PUT','DELETE','PATCH'])){
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
    $reponse = curl_exec($ch);
    curl_close($ch);
    return $reponse;
}

四、使用php composer的擴展guzzlehttp

composer require guzzlehttp/guzzle
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
 
echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
 
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
 
$promise->wait();

日常開發(fā)中我們盡量用方法三,自定義用curl處理網(wǎng)絡(luò)請求,或用composer的guzzlehttp擴展庫,有起來也很方便。

以上就是關(guān)于“PHP如何實現(xiàn)網(wǎng)絡(luò)請求”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI