PHP讀取遠程文件的4種方法


1. fopen, fread
1 if($file = fopen("http://www.example.com/", "r")) {
2 while(!feof ($file))
3 $data .= fread($file, 1024);
4 }
5 fclose($file);
2. file_get_contents
很簡單的一句話:
$data = file_get_contents("http://www.example.com/");
如果要限制超時時間,需要使用到它的$context參數
1 $opts = array('http' => array('timeout' => 30) );
2 $context = stream_context_create($opts);
3 $data = file_get_contents("http://www.example.com/", false, $context);
其中,第二個參數$use_include_path表示在php.ini設置的include_path中查找文件,使用false即可。
此外,本函數也可以發送POST數據:
1 $opts = array('http' => array(
2 'method' => 'POST',
3 'content' => 'x=1&y=2'));
4 $context = stream_context_create($opts);
5 $data = file_get_contents("http://www.example.com/", false, $context);
相對來說第二種方法比較快捷。以上兩種方法需要php.ini設置allow_url_fopen=On。
3. fsockopen, fwrite, fread
01 if($fp = fsockopen('www.example.com', 80, $errno, $errstr, 30)) {
02 $header = "GET /ip.php?ip=$ip HTTP/1.0rn";
03 $header .= "HOST: www.example.comrn";
04 $header .= "Connection: Closernrn";
05 fwrite($fp, $header);
06 stream_set_timeout($fp, 2);
07 while(!feof($fp))
08 $data .= fread($fp, 128);
09 fclose($fp);
10 }
本方法需要開啟php_sockets擴展
4. curl
1 $curl = curl_init();
2 curl_setopt($curl, CURLOPT_URL, "http://www.example.com/");
3 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
4 curl_setopt($curl, CURLOPT_TIMEOUT, 30);
5 $data = curl_exec($curl);
6 curl_close($curl);
curl也可用來發送POST數據及發送HTTP請求頭信息,以下是另一用例:
01 $curl = curl_init();
02 curl_setopt_array($curl, array(
03 CURLOPT_URL => "http://192.168.1.200/",
04 CURLOPT_RETURNTRANSFER => 1,
05 CURLOPT_POSTFIELDS => array('name'=>'Foo', 'password'=>'Bar'),
06 CURLOPT_POST => 1,
07 CURLOPT_HTTPHEADER => array('Host:www.example.com', 'Referer:www.example.com'),
08 );
09 $data = curl_exec($curl);
10 curl_close($curl);
本方法需要開啟php_curl擴展


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM