Home > Article > Backend Development > Five ways to request url in php
This article mainly introduces the five methods of requesting URLs in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.
Five methods:
The first three are the basic file operation functions of PHP
curl()
is a PHP extension that needs to be enabled and installed under Linux.
exec()
is executed The command wget under the linux command line downloads remote files
. The wget command failed when testing the local virtual machine to request http://www.baidu.com, but failed on the remote server. Yes, considering the problem of DNS resolution, I directly requested the IP and successfully downloaded the index.html file.
Only methods are provided here. The advantages and disadvantages require a detailed understanding of the functions and defects of each method.
1. fopen() function
$file = fopen("http://www.jb51.net", "r") or die("打开远程文件失败!"); while (!feof($file)) { $line = fgets($file, 1024); //使用正则匹配标题标记 if (preg_match("/<title>(.*)<\/title>/i", $line, $out)) { $title = $out[1]; //将标题标记中的标题字符取出 break; //退出循环,结束远程文件读取 } } fclose($file);
2 , file() function
$lines = file("http://www.jb51.net/article/48866.htm"); readfile(http://www.jb51.net/article/48866.htm);
##3. file_get_contents() function
$content = file_get_contents(http://www.jb51.net/article/48866.htm);
##4. Curl() requests remote url data
$url = "http://www.baidu.com"; $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $contents = curl_exec($ch); curl_close($ch);
5. exec() executes the command line command##
//exec("wget 220.181.111.188"); shell_exec("wget 220.181.111.188");
Related recommendations:
php implements c
url upload, download, https login
U method in thinkphp is generated according to routing rules
Detailed explanation of stepsPHP transfer session c
urlThe above is the detailed content of Five ways to request url in php. For more information, please follow other related articles on the PHP Chinese website!