Several ways to access url in php

小云云
Release: 2023-03-21 18:12:02
Original
12022 people have browsed it

This article mainly shares with you several methods of accessing URLs in PHP. There are four methods in total. I hope it can help 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 remote files will cause the CPU to surge. File_get_contents can actually 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 homepage information of the website can be obtained, not other pages)

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30); (!$fp) { echo "$errstr ($errno)
\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

Related recommendations:

php loop access url writing problem

php Method for garbled transcoding to trigger access to URL

Oracle’s database access Url: The difference between oci and thin

The above is the detailed content of Several ways to access url in php. 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!