Home > Backend Development > PHP Tutorial > 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)

不言
Release: 2023-04-03 17:00:01
Original
6469 people have browsed it

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;   
 }
Copy after login

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;
Copy after login

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;  
}
Copy after login

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);     
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template