This article mainly introduces you to the request URL in PHP five methods, respectively, with the fopen () function, the file () function, the file_get_contents () function, curl () request the remote URL data and exec () command line command, let's take a look at it, Hope to help everyone.
Five methods:
The first three types are PHP basic file manipulation functions
Curl () is a PHP extension that needs to be turned on, Linux needs to be installed
EXEC () executes the command under the Linux command line wget download the remote file
Where the wget command in the local virtual machine test request http://www.php.cn/, no success, on the remote server can, consider the problem of DNS resolution, and then directly request IP successfully downloaded the index.html file.
There are only methods available here, and the pros and cons of each method need to be understood in detail.
One, fopen () function
$file = fopen ("http://www.php.cn/", "R") or Die ("Open remote file failed!"); while (!feof ($file)) {$line = Fgets ($file, 1024);//use regular match headers to mark if (Preg_match ("/<title> (. *) <\/title>/i", $ Line, $out)) { $title = $out [1];//Remove the title character from the header tag to break;//exit the loop to end the remote file read}}fclose ($file);
Second, file () function
$lines = File ("http://www.php.cn/php-weizijiaocheng-386441.html"); ReadFile (http://www.php.cn/ php-weizijiaocheng-386441.html);
Three, file_get_contents () function
$content = file_get_contents (http://www.php.cn/php-weizijiaocheng-386441.html);
Four, 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);
V. EXEC () Execute command-line command
EXEC ("wget 220.181.111.188"); Shell_exec ("wget 220.181.111.188");