How to get remote files by php
This article will explain in detail how to obtain remote files from php. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Methods: 1, use "file_get_contents ($url)" statement to get; 2, open curl, use curl_init (), curl_setopt () and other functions to get; 3, use "fread (" $url "," rb "), 8192)" statement to get.
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); / / if Chinese garbled code occurs, use the following code / / $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 (ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); / / the following two lines / / curl_setopt ($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY) need to be added to the web page that needs to be tested by the user; / / curl_setopt ($ch, CURLOPT_USERPWD, US_NAME.": ".US _ PWD) $contents = curl_exec ($ch); curl_close ($ch); echo $contents
3.fopener-> 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 distinction analysis:
1. To use file_get_contents and fopen, allow_url_fopen must be enabled in space.
Method: edit php.ini and set allow_url_fopen = On,allow_url_fopen. Neither fopen nor file_get_contents can open remote files when closed.
2. To use curl, you must open curl in space.
Method: modify php.ini under WIN to remove the semicolon before extension=php_curl.dll, and copy ssleay32.dll and libeay32.dll to C:\ WINDOWS\ system32
The curl extension should be installed under Linux.
It is recommended to use the file_get_contents () method when opening URL to optimize the opening speed.
This is the end of the article on "how to get remote files from php". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.