几种php访问url的方法

小云云
小云云 原创
2023-03-21 18:12:02 9524浏览

本文主要和大家分享几种php访问url的方法,一共有四种,希望能帮助到大家。

1、fopen方式

 //访问指定URL函数
function access_url($url) 
{        if($url=='') return false;       
$fp = fopen($url, 'r') or exit('Open url faild!');        
if($fp){       while(!feof($fp)) {           
 $file .= fgets($fp) . "";       }       
 fclose($fp);        }      
 return $file;   }

2、file_get_contents方式 (打开远程文件的时候会造成CPU飙升。file_get_contents其实也可以post)

//以post方式获取url
$data = array ('foo' => 'bar');
$data = http_build_query($data);
$opts['http'] = array (
  'method' => 'POST',
  'header'=> "Content-type:application/x-www-form-urlencodedrn".
  "Content-Length: " . strlen($data) . "rn",
  'content' => $data
);
$context = stream_context_create($opts);
$html = file_get_contents('http://localhost/test.html', false, $context);
echo $html;

3、curl方式

  
function curl_file_get_contents($durl){  
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $durl);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回    
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回    
    $data = curl_exec($ch);  
    curl_close($ch);  
    return $data;  
}

4、fsockopen方式(只能获取网站主页信息,其他页面不可以)

 $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);     
 (!$fp) {     
    echo "$errstr ($errno)<br />\n";     
 }else {     
    $out="GET / HTTP/1.1\r\n";     
    $out.="Host: www.example.com\r\n";     
    $out.="Connection: Close\r\n\r\n";     
    fwrite($fp, $out);     
    while (!feof($fp)) {     
        echo fgets($fp, 128);     
    }  
    fclose($fp);     
 }

相关推荐:

php循环访问url写法问题

php 乱码转码 触发访问url的方法

Oracle的数据库访问Url: oci 和 thin 的区别

以上就是几种php访问url的方法的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。