Home Backend Development PHP Tutorial Comparison of curl, fsocket, file_get_content functions in php

Comparison of curl, fsocket, file_get_content functions in php

Jul 25, 2016 am 09:12 AM

When I was working on a web thief program recently, I discovered that file_get_content could no longer meet the needs. I think that when reading remote content, file_get_content is not as good as curl except for being more convenient to use than curl

To capture remote content, I have been using the file_get_content function before. In fact, I have known about the existence of such a good thing as curl, but after taking a look, I felt that it is quite complicated to use. It is not as simple as file_get_content, and the demand is not big. So I didn't learn to use curl.

Some comparisons between curl and file_get_content in php Main differences: Curl supports many protocols, including FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE and LDAP. In other words, it can do many things that file_get_content cannot do. Curl can achieve remote acquisition and collection of content in PHP; implement FTP upload and download of PHP web version; implement simulated login; implement interface docking (API), data transmission; implement simulated cookies; download file breakpoint resume transfer, etc., the function is very powerful . After understanding some basic uses of curl, I found that it is not difficult. It is just a little difficult to remember some of the setting parameters, but we can just remember a few commonly used ones. Turn on curl: Because PHP does not support the curl function by default, if you want to use curl, you first need to enable this function in php.ini, that is, remove the semicolon in front of ;extension= php_curl.dll, then save and restart apache/iis . Basic syntax:

  1. $my_curl = curl_init(); //Initialize a curl object
  2. curl_setopt($my_curl, CURLOPT_URL, "http://bbs.it-home.org"); //Set what you need to crawl URL
  3. curl_setopt($my_curl,CURLOPT_RETURNTRANSFER,1); //Set whether to save the result to a string or output it to the screen. 1 means saving the result to a string
  4. $str = curl_exec($curl); //Execute Request
  5. echo $str; //Output the crawled results
  6. curl_close($curl); //Close the url request
Copy code

Recently, I need to obtain music data from other people's websites. I used the file_get_contents function, but I always encountered the problem of failure to obtain it. Although I set the timeout according to the examples in the manual, it does not work most of the time:

  1. $config['context'] = stream_context_create(array('http' => array('method' => "GET",
  2. 'timeout' => 5//This timeout period is not Stable, often doesn't work
  3. )
  4. ));
Copy code

At this time, if I look at the server's connection pool, I will find a bunch of similar errors, which gives me a huge headache: file_get_contents(http://***): failed to open stream… Now I use the curl library instead and write a function replacement:

  1. function curl_file_get_contents($durl){
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_URL, $durl);
  4. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  5. curl_setopt($ch, Curlopt_useragent, _Userager _); exec ($ ch);
  6. CURL_CLOSE ($ ch);
  7. Ereturn $ r;
  8. }
  9. Copy the code
So no more problems except real network issues. Here is a test others have done on curl and file_get_contents: The number of seconds file_get_contents takes to crawl google.com: 2.31319094 2.30374217 2.21512604 3.30553889 2.30124092 Curl usage time: 0.68719101 0.64675593 0.64326 0.81983113 0.63956594 Differs greatly? Haha, from my experience, these two tools are not only different in speed, but also in stability. It is recommended that friends who have high requirements for the stability of network data capture use the curl_file_get_contents function above. It is not only stable and fast, but also can fake the browser to spoof the target address!
Speaking of the usage of curl and file_get_contents, they have been mentioned in previous articles. Here are a few good articles recommended for your reference:

How to set up PHP file_get_contents timeout processing

    Solution to php file_get_contents grabbing garbled Gzip web pages
  • Solution to file_get_contents timeout problem in php
  • How to set PHP file_get_contents timeout
  • Example of php file_get_content compatibility detection
  • php file_get_contents code to capture page information
  • php file_get_contents function code to capture page information
  • Method 1: Use file_get_contents to get the content in get mode

$url='http://www.domain.com/';
  • $html = file_get_contents($url);
  • echo $html;
  • ?>
  • Copy code
  • Method 2: Open the url with fopen and get the content with get method

    1. $fp = fopen($url, 'r');
    2. stream_get_meta_data($fp);
    3. while(!feof($fp)) {
    4. $result .= fgets($ fp, 1024);
    5. }
    6. echo "url body: $result";
    7. fclose($fp);
    8. ?>
    Copy code

    Method 3: Use the file_get_contents function to get the url in post mode

    1. $data = array ('foo' => 'bar');
    2. $data = http_build_query($data);
    3. $opts = array (
    4. 'http' => array (
    5. 'method' => 'POST',
    6. 'header'=> "Content-type: application/x-www-form-urlencodedrn" .
    7. "Content-Length: " . strlen($data) . "rn",
    8. 'content' => $data
    9. )
    10. );
    11. $context = stream_context_create($opts);
    12. $html = file_get_contents('http://localhost/e/admin/test.html', false, $context);
    13. echo $html;
    14. ?>
    Copy code

    Method 4: Use the fsockopen function to open the url and get the complete data in get mode, including header and body

    1. function get_url ($url,$cookie=false)
    2. {
    3. $url = parse_url($url);
    4. $query = $url[path]."?".$url [query];
    5. echo "Query:".$query;
    6. $fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
    7. if (!$fp) {
    8. return false;
    9. } else {
    10. $request = "GET $query HTTP/1.1rn";
    11. $request .= "Host: $url[host]rn";
    12. $request .= "Connection: Closern";
    13. if($cookie) $request.="Cookie: $cookien";
    14. $request.="rn";
    15. fwrite($fp,$request);
    16. while()) {
    17. $ result .= @fgets($fp, 1024);
    18. }
    19. fclose($fp);
    20. return $result;
    21. }
    22. }
    23. //Get the html part of the url, remove the header
    24. function GetUrlHTML($url,$cookie =false)
    25. {
    26. $rowdata = get_url($url,$cookie);
    27. if($rowdata)
    28. {
    29. $body= stristr($rowdata,"rnrn");
    30. $body=substr($body,4 ,strlen($body));
    31. return $body;
    32. }
    33. return false;
    34. }
    35. ?>
    Copy code

    Method 5: Use the fsockopen function to open the url and get the complete data in POST mode , including header and body

    1. function HTTP_Post($URL,$data,$cookie, $referrer="")
    2. {
    3. // parsing the given URL
    4. $URL_Info=parse_url($URL);
    5. / / Building referrer
    6. if($referrer=="") // if not given use this script as referrer
    7. $referrer="111″;
    8. // making string from $data
    9. foreach($data as $key=> $value)
    10. $values[]="$key=".urlencode($value);
    11. $data_string=implode("&",$values);
    12. // Find out which port is needed – if not given use standard (=80)
    13. if(!isset($URL_Info["port"]))
    14. $URL_Info["port"]=80;
    15. // building POST-request:
    16. $request.="POST ".$URL_Info[ "path"]." HTTP/1.1n";
    17. $request.="Host: ".$URL_Info["host"]."n";
    18. $request.="Referer: $referern";
    19. $request. ="Content-type: application/x-www-form-urlencodedn";
    20. $request.="Content-length: ".strlen($data_string)."n";
    21. $request.="Connection: closen";
    22. $request.="Cookie: $cookien";
    23. $request.="n";
    24. $request.=$data_string."n";
    25. $fp = fsockopen($URL_Info["host"],$URL_Info[ "port"]);
    26. fputs($fp, $request);
    27. while(!feof($fp)) {
    28. $result .= fgets($fp, 1024);
    29. }
    30. fclose($fp);
    31. return $result;
    32. }
    33. ?>
    Copy code

    Method 6: Use the curl library. Before using the curl library, you may need to check whether the curl extension has been turned on in php.ini

    1. $ch = curl_init();
    2. $timeout = 5;
    3. curl_setopt ($ch, CURLOPT_URL, 'http://www.domain.com/');
    4. curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1);
    5. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    6. $file_contents = curl_exec($ch);
    7. curl_close($ch);
    8. echo $file_contents;
    9. ?>
    Copy Code

    The three functions of curl, fsockopen and file_get_contents in php can all realize the collection of simulated speeches. What is the difference between the three, or is there anything to pay attention to? Zhao Yongbin: Sometimes when using file_get_contents() to call external files, it is easy to report an error due to timeout. Just change it to curl. The specific reason is not clear. The efficiency of curl is higher than file_get_contents() and fsockopen(). The reason is that CURL will automatically cache DNS information (the highlight is for me to test personally)

    Fan Jiapeng: file_get_contents curl fsockopen Selective operations in the current requested environment, without generalization: Let’s look at the KBI application developed by our company: Just started using: file_get_contents Later adopted: fsockopen Last used till now: curl (Remotely) My personal understanding is as follows (please point out if it is wrong, please add if it is not correct) file_get_contents needs to enable allow_url_fopen in php.ini. When requesting http, http_fopen_wrapper is used. It is ok if you don't know keeplive.curl. file_get_contents() has high single execution efficiency and returns information without header. This is no problem when reading ordinary files, but problems will occur when reading remote files. If you want to make a continuous connection, request multiple pages multiple times. Then there will be problems with file_get_contents and fopen. The obtained content may also be incorrect. So when doing some similar collection work, there will definitely be a problem. Sock is relatively low-level, troublesome to configure, and difficult to operate. Return complete information.

    Pan Shaoning-Tencent: Although file_get_contents can get the content of a certain URL, it cannot post get it. Curl can post and get. Head information can also be obtained Sockets are lower level. Can be set to interact based on UDP or TCP protocol If file_get_contents and curl can do it, socket can do it. What socket can do, curl may not be able to do. file_get_contents more often just pulls data. It is more efficient and simpler. I have also encountered Zhao's situation. I set the host through CURL and it was OK. This has something to do with the network environment.

    That’s it. The above introduces the similarities and differences in the usage of url, fsocket, and file_get_content functions in PHP through examples. I hope it will be helpful to everyone.



    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    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)

    11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

    Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

    Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

    Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

    Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

    Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

    Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

    This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

    Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

    Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

    cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

    The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

    12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

    Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

    Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

    The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

    See all articles