Home  >  Article  >  Backend Development  >  What are the methods for obtaining remote files in php

What are the methods for obtaining remote files in php

青灯夜游
青灯夜游Original
2021-09-22 19:42:103389browse

Method: 1. Use the "file_get_contents($url)" statement to obtain; 2. Turn on curl and use curl_init(), curl_setopt() and other functions to obtain; 3. Use "fread(fopen("$url" ,"rb"),8192)" statement to obtain.

What are the methods for obtaining remote files in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

1.file_get_contents

$url = 'http://www.xxx.com/';
$contents = file_get_contents($url);
//如果出现中文乱码使用下面代码
//$getcontent = iconv(“gb2312″, “utf-8″,file_get_contents($url));
//echo $getcontent;
echo $contents;
?>

2.curl

url = “http://www.xxx.com/”;
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//在需要用户检测的网页里需要增加下面两行
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_USERPWD, US_NAME.”:”.US_PWD);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;

3.fopen->fread-> fclose

$handle = fopen (“http://www.xxx.com/”, “rb”);
$contents = “”;
do {
$data = fread($handle, 8192);
if (strlen($data) == 0)
{break;}
$contents .= $data;
} while(true);
fclose ($handle);
echo $contents;

file_get_contents, fopen, curl difference analysis:

1, Usefile_get_contents and fopen must be opened allow_url_fopen.

Method: Edit php.ini and set allow_url_fopen = On, allow_url_fopen When closed, neither fopen nor file_get_contents can be opened remote file.

2,

Use curlmust open spacecurl .

Method: Modify

php.ini under WIN and change extension=php_curl.dllRemove the semicolon in front, and you need to copy ssleay32.dll and libeay32.dll to C:\WINDOWS\system32; to

Linux

To install the curl extension.

It is recommended to use the

file_get_contents() method when opening URL to optimize the opening speed Recommended learning: "

PHP Video Tutorial

"

The above is the detailed content of What are the methods for obtaining remote files 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