Home  >  Article  >  Backend Development  >  How to access URL in PHP? Summary of methods for accessing URLs in php (code)

How to access URL in PHP? Summary of methods for accessing URLs in php (code)

不言
不言Original
2018-08-06 16:08:196438browse

This article introduces to you how to access URL in PHP? The summary (code) of the method of accessing URL in PHP has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. fopen method

//访问指定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 method (opening a remote file will cause the CPU to surge. File_get_contents actually also Can 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 method

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 method (only the website homepage information can be obtained , other pages are not allowed)

$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);     
}

Recommended related articles:

phpHow to send emails using PHPMailer (with code)

How to hide the TP entry file under Ubuntu system

The above is the detailed content of How to access URL in PHP? Summary of methods for accessing URLs in php (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn