Home > Backend Development > PHP Tutorial > Summary of methods for requesting url in php

Summary of methods for requesting url in php

小云云
Release: 2023-03-20 06:04:01
Original
4886 people have browsed it

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 //m.sbmmt.com/, 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("//m.sbmmt.com/", "r") or die("打开远程文件失败!");
while (!feof($file)) {
 $line = fgets($file, 1024);
 //使用正则匹配标题标记
 if (preg_match("/<title>(.*)<\/title>/i", $line, $out)) { 
 $title = $out[1]; //将标题标记中的标题字符取出
 break; //退出循环,结束远程文件读取
 }
}
fclose($file);
Copy after login

2. file() function

$lines = file("//m.sbmmt.com/php-weizijiaocheng-386441.html");
readfile(//m.sbmmt.com/php-weizijiaocheng-386441.html);
Copy after login

3. file_get_contents() function

$content = file_get_contents(//m.sbmmt.com/php-weizijiaocheng-386441.html);
Copy after login

4. curl() Request remote url data

$url = "//m.sbmmt.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);
Copy after login

5. exec() execute command line command

//exec("wget 220.181.111.188");
shell_exec("wget 220.181.111.188");
Copy after login

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!

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