php下請求url的幾種方式

Donne發表於2019-02-16

總結了5種方法:

  • 前三種都是php基本的檔案操作函式

  • curl()是php擴充套件需要開啟,linux下需要安裝

  • exec()執行的是linux命令列下的命令wget下載遠端檔案

其中wget命令在本地虛機測試請求http://www.baidu.com時,沒有成功,在遠端伺服器上卻可以,考慮時DNS解析的問題,於是直接請求IP成功下載了index.html的檔案。

這裡只提供了方法,其中的優缺點需要詳細瞭解每一個方法的功能和缺陷。

1.fopen()函式

$file = fopen("http://www.jb51.net", "r") or die("開啟遠端檔案失敗!");
while (!feof($file)) {
    $line = fgets($file, 1024);
    //使用正則匹配標題標記
    if (preg_match("/<title>(.*)</title>/i", $line, $out)) {     
        $title = $out[1];     //將標題標記中的標題字元取出
        break;     //退出迴圈,結束遠端檔案讀取
    }
}
fclose($file);

2.file()函式

$lines = file("http://www.jb51.net/article/48866.htm");
readfile("http://www.jb51.net/article/48866.htm");

3.file_get_contents()函式

$content = file_get_contents("http://www.jb51.net/article/48866.htm");

4.curl() 請求遠端url資料

$url = "http://www.baidu.com";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$contents = curl_exec($ch);
curl_close($ch);

5.exec() 執行命令列命令

//exec("wget 220.181.111.188");
shell_exec("wget 220.181.111.188");

相關文章