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扩展