This article mainly introduces you to the five methods of requesting URLs in PHP, namely using the fopen() function, file() function, file_get_contents() function, curl() to request remote URL data and exec() to execute the command line. Command, let’s take a look at it below, I hope it can help everyone.
Five methods:
The first three are PHP’s basic file operation functions
curl( ) is the PHP extension that needs to be enabled and installed under Linux
exec() executes the command wget under the Linux command line to download remote files
The wget command failed when testing the local virtual machine to request http://www.php.cn/, but it worked on the remote server. Considering the problem of DNS resolution, I directly requested the IP and successfully downloaded index.html. document.
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.php.cn/", "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.php.cn/php-weizijiaocheng-386441.html"); readfile(http://www.php.cn/php-weizijiaocheng-386441.html);
3. file_get_contents() function
$content = file_get_contents(http://www.php.cn/php-weizijiaocheng-386441.html);
4. curl() Request remote url data
$url = "http://www.php.cn/"; $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() execute command line command
//exec("wget 220.181.111.188"); shell_exec("wget 220.181.111.188");
Related recommendations:
What are the methods for requesting url in php
The above is the detailed content of Summary of methods for requesting url in php. For more information, please follow other related articles on the PHP Chinese website!