search
HomeBackend DevelopmentPHP TutorialWhat are the methods to request url in php

What are the methods to request url in php

Jul 16, 2017 pm 04:39 PM
phpSummarizeSkill

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

<?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(); 
?>

Sample code 2: Use fopen to open the url,

Get the content by get method

<? 
$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); 
?>

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

<?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; 
?>

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

<? 
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; 
} 
?>

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

$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);

2. file() function


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

3. file_get_contents() function

##

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

4. curl() requests remote url data

$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);

5. exec() executes the command line Command

//exec("wget 220.181.111.188");
shell_exec("wget 220.181.111.188");

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
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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

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 Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools