PHP three ways to read remote files

Source: Internet
Author: User
Tags fread
PHP read remote file Several methods summary and the difference analysis.

1.file_get_contents

$url = ' http://www.xxx.com/';
$contents = file_get_contents ($url);
If there is a garbled Chinese 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;
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_connecttimeout, $timeout);//Add the following two lines to a Web page that requires user testing
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. Use file_get_contents and fopen to open the Allow_url_fopen.

Method: Edit PHP.ini, set allow_url_fopen = On,allow_url_fopen Close when fopen and file_get_contents cannot open remote files.

2. Use curl to have space to turn on curl.

Method: Win under Modify PHP.ini, Extension=php_curl.dll front of the semicolon removed, and need to copy Ssleay32.dll and Libeay32.dll to C:\WINDOWS\system32;

Install the Curl extension under Linux.

We recommend that you use the file_get_contents () method when you open the URL to optimize the open speed

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.