Home Backend Development PHP Tutorial What are the methods to request url in php

What are the methods to request url in php

Jul 16, 2017 pm 04:39 PM
php Summarize Skill

A summary of several methods of opening URL addresses in PHP. The functions here are mainly used for functions such as thief collection.

1: Use file_get_contents

Get the content in get mode

1

2

3

4

5

6

7

8

9

10

<?php

$url=&#39;www.baidu.com/&#39;;

$html = file_get_contents($url);

//print_r($http_response_header);

ec($html);

printhr();

printarr($http_response_header);

  

printhr();

?>

Copy after login

Sample code 2: Use fopen to open the url,

Get the content by get method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<?

$fp = fopen($url, &#39;r&#39;);

  

printarr(stream_get_meta_data($fp));

printhr();

while(!feof($fp)) {

  

$result .= fgets($fp, 1024);

}

echo "url body: $result";

  

printhr();

fclose($fp);

?>

Copy after login

Sample code 3: Use the file_get_contents function to get the url by post method

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<?php

$data = array (&#39;foo&#39; =>

&#39;bar&#39;);

$data = http_build_query($data);

$opts = array (

&#39;http&#39;

=> array (

&#39;method&#39; => &#39;POST&#39;,

&#39;header&#39;=> "Content-type:

application/x-www-form-urlencoded" .

"Content-Length: " . strlen($data) .

"",

&#39;content&#39; => $data

),

);

$context =

stream_context_create($opts);

$html =

file_get_contents(&#39;localhost/e/admin/test.html&#39;, false, $context);

  

echo $html;

?>

Copy after login

Sample code 4: Use the fsockopen function to open the url, and get the complete data by get method, including header and body

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<?

function get_url

($url,$cookie=false) {

$url = parse_url($url);

$query =

$url[path]."?".$url[query];

ec("Query:".$query);

$fp = fsockopen(

$url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);

if (!$fp) {

  

return false;

} else {

$request = "GET $query HTTP/1.1";

  

$request .= "Host: $url[host]";

$request .= "Connection: Close";

  

if($cookie) $request.="Cookie: $cookie\n";

$request.="";

  

fwrite($fp,$request);

while(!@feof($fp)) {

$result .= @fgets($fp,

1024);

}

fclose($fp);

return $result;

}

}

//获取url的html部分,去掉header

function GetUrlHTML($url,$cookie=false) {

  

$rowdata = get_url($url,$cookie);

if($rowdata)

{

$body=

stristr($rowdata,"");

$body=substr($body,4,strlen($body));

return $body;

}

return false;

}

?>

Copy after login

I encountered a problem recently during development. Line 4 of the program will request a URL. By searching for relevant information, I found that there are many methods. This article introduces you to five ways to request URLs in PHP. Three methods are to use fopen() function, file() function, file_get_contents() function, curl() to request remote url data and exec() to execute command line commands

This article mainly I will introduce you to the five methods of requesting URLs in PHP and share them for your reference and study. Without further ado, let’s take a look at the detailed introduction:

Five methods :

  • The first three are the basic file operation functions of PHP

  • curl()It is the php extension that needs to be enabled, and it needs to be installed under Linux

  • exec()The command wget download under the Linux command line is executedRemote file

The wget command failed when testing the local virtual machine to request www.baidu.com, but it worked on the remote server. DNS resolution was considered. problem, so 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

1

2

3

4

5

6

7

8

9

10

$file = fopen("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);

Copy after login

2. file() function


1

2

$lines = file("www.jb51.net/article/48866.htm");

readfile(www.jb51.net/article/48866.htm);

Copy after login

3. file_get_contents() function

##

1

$content = file_get_contents(www.jb51.net/article/48866.htm);

Copy after login

4. curl() requests remote url data

1

2

3

4

5

6

7

8

$url = "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);

Copy after login

5. exec() executes the command line Command

1

2

//exec("wget 220.181.111.188");

shell_exec("wget 220.181.111.188");

Copy after login

The above is the detailed content of What are the methods to request url in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

How to use type traits in C? How to use type traits in C? Apr 28, 2025 pm 08:18 PM

typetraits are used in C for compile-time type checking and operation, improving code flexibility and type safety. 1) Type judgment is performed through std::is_integral and std::is_floating_point to achieve efficient type checking and output. 2) Use std::is_trivially_copyable to optimize vector copy and select different copy strategies according to the type. 3) Pay attention to compile-time decision-making, type safety, performance optimization and code complexity. Reasonable use of typetraits can greatly improve code quality.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

See all articles