HTTP Class for PHP (supports both cURL and fsockopen)

Jan 20, 2008

Feb 2009: A couple bugs have been fixed and library updated.

This is a wrapper HTTP class that uses either cURL or fsockopen to harvest resources from the web. It supports a handy subset of functionalists of HTTP that are mostly needed in day to day coding. Scripts who need to communicate with other servers will find it useful. If you’re looking to invoke any RESTful API and don’t want to bother adding a bunch of libraries for that simple thing, just put this class and you’re set.

Download

Detailed documentation can be found here. And you can download the source from here.

Update

Class added in Orchid – “PHP framwork for the rest of us”

Features

  • Can use both cURL and fsockopen.
  • Degrades to fsockopen if cURL not enabled.
  • Supports HTTP Basic authentication.
  • Supports defining custom request headers.
  • Supports defining connection timeout values.
  • Supports defining user agent and referral values.
  • Supports both user-defined and persistent cookies.
  • Supports secure connections (HTTPS) with and without cURL.
  • Supports adding requests parameters for both GET and POST.
  • Supports automatic redirection (maximum redirect can be defined).
  • Returns HTTP response headers and response body data separately.

Example 1 – Simple Get (Facebook Application List)

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6:
   7: $http->execute('http://www.facebook.com/apps/index.php?sort=6');
   8: echo ($http->error) ? $http->error : $http->result;
   9:
  10: ?>

Example 2 – Invoking Yahoo Term Extraction API

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6:
   7: $http->addParam('appid'   , 'a_really_random_yahoo_app_id');
   8: $http->addParam('context' , 'I am happy because I bought a new car');
   9: $http->addParam('output'  , 'xml');
  10:
  11: $http->execute('http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction');
  12: echo ($http->error) ? $http->error : $http->result;
  13:
  14: ?>

Example 3 – Logging into Basecamp (without using cURL!)

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6:
   7: $http->useCurl(false);
   8: $http->setMethod('POST');
   9:
  10: $http->addParam('user_name', 'emran');
  11: $http->addParam('password', 'hasan');
  12:
  13: $http->setReferrer('https://someproject.projectpath.com/login');
  14: $http->execute('https://someproject.projectpath.com/login/authenticate');
  15:
  16: echo ($http->error) ? $http->error : $http->result;
  17:
  18: ?>

Example 4 – Getting a protected feed

   1: <?php
   2:
   3: include_once('class.http.php');
   4:
   5: $http = new Http();
   6: $http->setAuth('emran', 'hasan');
   7:
   8: $http->execute('http://www.someblog.com/protected/feed.xml');
   9: echo ($http->error) ? $http->error : $http->result;
  10:
  11: ?>

There are 45 comments in this article:

  1. 20/01/2008Omi Azad says:

    You can add this function in Orchid framework. :)

  2. 20/01/2008Emran Hasan says:

    Yeah Omi bhai – i’ve already planned that :) Just not been able to log into the SVN lately :(

  3. 20/01/2008masud says:

    Great job Emran vai. Finally you released this. :)
    yea its a good idea if you add this to orchid framework. :)

    cool man :)

  4. 21/01/2008H2 says:

    Well done Batman! A very good one. I was thinking that we need such a class library for orchid. Can I please add your class with default distribution?

    You are doing excellent. Keep up the good work. Godspeed.

  5. 21/01/2008Emran Hasan says:

    Thanks Hasin. And yes, i would be honored if this is added to orchid.

  6. 21/01/2008Jahedur Rahman says:

    Wow, It’s a nice theme. Tobe menu gula dekhte ekto asubidha hocche r ki :)

  7. 21/01/2008Anis uddin Ahmad says:

    Simply GENIUS!
    Excellent structure, easy to use and ???????? documentation.

  8. 24/01/2008ASP mit Javascript einbinden? - jswelt - Forum (Javascript, PHP, MySQL, AJAX, Webdesign) says:

    [...] Allerdings kannst du das selbe auch mit PHP machen, indem du einen HTTP-request ausf?hrst. Diese Klasse kann dir dabei m?glicherweise die Arbeit vereinfachen (du kannst den get-Aufruf nat?rlich auch [...]

  9. 25/01/2008  New Addition - http object by Orchid says:

    [...] goes to Emran for contributing this [...]

  10. 26/01/2008Weekend Links -- CSS & Multiple Background Images, Programming Book Profits, PHP HTTP Class, MooTools 1.2, IE8's New Meta Tag, and Domain Tasting says:

    [...] http://www.phpfour.com/blog/2008/01/20/php-http-class/ [...]

  11. 13/02/2008Jack says:

    Thanks for the code. I found it in the Code Igniter forums. I turned it into a library for use in my most recent web app.

  12. 13/02/2008Emran Hasan says:

    @jack: Great to know that it came to help you exactly in the manner i expected it would. Great to know that you’re using it in your project :)

  13. 14/02/2008Edmonds Commerce Blog says:

    Building Spiders: Grab Data, Post Forms and Interact with Web Sites Automatically…

    One of the most useful and powerful things you can do with PHP is to create a programme which will simulate a web browser and can grab data, post data to forms and generally interact with other web sites – automatically.
    For PHP to be able to work like…

  14. 15/02/2008tapos says:

    cool work.

  15. 27/02/2008HTTP Class for PHP | AplicacionesWeb says:

    [...] HTTP Class for PHP – supports both cURL and fsockopen Este artículo fue posteado el Martes, Febrero 26th, 2008 a las 5:28 pm , Por Juan Jorquera , y lo encuentras en las etiquetas OpenSource, cron, php. puedes seguir los comentarios de este artículo en su feed . Puedes dejar tu comentario, o hacer un “trackback” desde tu sitio web. [...]

  16. 12/03/2008Andy Gelox says:

    Thx for this awesome class. How to make it aouto detect for curl or dsockopen ?

  17. 12/03/2008Emran Hasan says:

    @Andy Gelox: You’re welcome. The class tries to use cURL by default, but if cURL is not installed, it automatically falls back to fsockopen. And you can specify by yourself in case you need to. Cheers!

  18. 15/04/2008Richard says:

    When use the class ,I notice
    the cURL require a website need longer time then fsockect.is it?

  19. 27/06/2008H-BES says:

    Hi,

    with allow redirect set to true if i call a page with status code 302 i can’t read the headers of destination page, i read only the headers of first page.

    it’s normal?

    can you help me?

    Thanks

    ciao
    riccardo

  20. 7/10/2008Brainbug says:

    Thanks for sharing the class.

    It is quite helpful in php4 and php5. Love how it degrades automatically if there is no CURL. Have you though of supporting stream wrappers?

  21. 9/10/2008Vince says:

    It seems that fsockopen method doesn't follow redirects.

  22. 11/10/2008Md Emran Hasan (phpfour) says:

    Well, it should follow redirects with or without cURL. I will have a look
    into it and will update the source if needed. Thanks

  23. 27/11/2008Eydun says:

    Is it possible with this class to post data, so they can be fetch on the other side with: file_get_contents(“php://input”)?

  24. 13/12/2008pwb says:

    What's the point of cURL if fsockopen works?

  25. 28/01/2009David Kierznowski says:

    Any reason the redirects on fsockopen route don't support 301 redirects?

    –snip–
    if ($this->status == '302' && $this->redirect == TRUE)
    –snip–

  26. 18/02/2009Md Emran Hasan (phpfour) says:

    Fixed. Thanks for noticing.

  27. 18/02/2009Md Emran Hasan (phpfour) says:

    Yes, it's similar to how you add a param:

    $http-&gt;addCookie(&#39;logged_in_user&#39;  , &#39;747&#39;);
  28. 18/02/2009Md Emran Hasan (phpfour) says:

    The library supports both, so it's the choice of the dev :)

  29. 22/04/2009Dean says:

    Thanks for making this useful class available. I was wondering if there's a way to download a zip file using this utility – to be unzipped later.

  30. 21/05/2009sue says:

    Hi Emran,

    Thanks for this class. It definetly makes code simple. Please see my code below(just used your example with little tweaks).

    I have couple of questions:

    1) We have special chars in password. Can i use it directly.
    2) We have SSO authentication. After authenticating it will forward to index.jsp page. When I use the below code, even though I specify userId/pswd, it is not authenticating. It is stopping at the login page. Can you please guide me how to come over this. Thanks.

    $http = new Http();
    $http->useCurl(false);
    $http->setMethod('GET');
    $http->addParam('user_name', 'test.id');
    $http->addParam('password', 'test!!pwd');
    $http->followRedirects(true);
    //$http->setReferrer('https://www.test.com/suite/portal/index.jsp&#39 ;) ;
    $http->execute('https://www.test.com/suite/portal/index.jsp&#39 ;) ;

    echo ($http->error) ? $http->error : $http->result;

  31. 27/05/2009Antwort auf "$HTTP_USER_AGENT" mittels php emulieren - php.de says:

    [...] kann ich dir folgende API empfehlen: HTTP Class for PHP (supports both cURL and fsockopen) | Md Emran Hasan (phpfour) Dort kannst du einstellen, welche Browserkennung gesendet wird. __________________ Kreativität [...]

  32. 29/06/2009bill says:

    That is one fine piece of code. I am very new to PHP and that will make my life so much simpler. I just have one question, How do i go about using proxies in it? Sorry if it is right in front of me but I have only been trying my hand a PHP for a few weeks now.

  33. 21/08/2009Md Emran Hasan (phpfour) says:

    Thanks for your comment. Unfortunately, proxies have not been implemented yet. Hope to add soon.

  34. 21/08/2009Md Emran Hasan (phpfour) says:

    Thanks for your comment. Special character on password should work okay as I've done so before. Regarding your login issue, I'm afraid it needs to be inspected more closely. Email me if you think you need my help on this.

  35. 22/10/2009Custom login form (authentication) to Basecamp (using PHP, no cURL!, no OpenID) « DocuView - document management system says:

    [...] research. I have looked at libraries/wrappers such as “Basecamp PHP API” and “HTTP class for PHP“, both have their advantages but didn’t do what I needed out-of-the-box. I have studied [...]

  36. 23/04/2010MiniGod says:

    Hey. I’ve been trying out your class, but i get an error on most websites:
    “501 Not Implemented” or “404 Bad Request” with the body “Method Not Implemented”.
    I get that last error in your own test_fbapp.php script.

    I do not know why i get this. Do you?
    Same error in both PHP 5.3.0 and PHP 5.2.11.

  37. 23/04/2010MiniGod says:

    Oh. And i also get a few warnings. Mostly “Undefined variable: cookieString”, also “Undefined index: transfer-encoding” etc….

  38. 23/04/2010Emran Hasan says:

    @MiniGod – The class has not been updated for a long time and does have a few more issues. I’d suggest you use the PECL HTTP extension – it’s a good one and these days I use that too.

  39. 16/05/2010Code Updates (HTTP class, Extended CodeIgniter Model, Cross-domain AJAX transport) | PHP Tutorials says:

    [...] original post is here for [...]

  40. 7/07/2010motobineuse says:

    i love this bog, i just bookmarked it to my delicious, thank you for posting this.

  41. 30/08/2011Plsnhat says:

    There’s an error: When trying to do a request with an url not available, the following code will return false for $content:

    // Get the target contents
    $content = curl_exec($ch);

    As the result, the following code is not valid (because $contentArray is not existing):

    $this->_parseHeaders($contentArray[count($contentArray) - 2]);

    You can fix this bug by using the following code at the end of execute():

    // Get the target contents
    $content = curl_exec($ch);

    // Store the error (is any)
    $this->_setError(curl_error($ch));

    // Check if could not load content
    if($content===false){
    throw new httpCurlExecFailed($this->error);
    }
    $contentArray = explode(“\r\n\r\n”, $content);

    // Get the request info
    $status = curl_getinfo($ch);

    // Store the contents
    $this->result = $contentArray[count($contentArray) - 1];

    // Parse the headers
    $this->_parseHeaders($contentArray[count($contentArray) - 2]);

    // Close PHP cURL handle
    curl_close($ch);

    You only need the following class:

    You may now fetch this exception:

    try {
    $req->execute($url);
    } catch(httpCurlExecFailed $e){
    echo “Error while executing request: ” . $e->getMessage . “\r\n”;
    }

  42. 30/08/2011Plsnhat says:

    To prevent E_DEPRECATED notice, you should replace:

    !eregi($match = “^http/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$”, $headers[0], $matches)

    with:

    if(!preg_match(“/^http\/[0-9]+\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)$/i”, $headers[0], $matches))

  43. 30/08/2011Plsnhat says:

    To make custom headers possible, add the method:

    /**
    * Add a header to the request
    *
    * @param string Name of header
    * @param string Value of header
    * @return void
    */
    function addHeader($name, $value){
    if(!empty($name) && !empty($value)){
    $this->headers[] = $name . “: ” . $value;
    }
    }

    In method execute() add

    curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); // Set custom headers

    after

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return in string

    and

    // Set custom headers
    foreach($this->headers as $header){
    $requestHeader .= $header;
    }

    after

    $requestHeader .= “Content-Type: application/x-www-form-urlencoded\r\n”;

    Be aware: It will not be checked whether you will overwrite default headers! So be cautious!

  44. 8/10/2011Jannik says:

    Hello,

    this Class is excellent:

    Could you tell me, why Facebook keeps saying: Cookies not enabled?

    I’ve been using it like this:

    setMethod(‘POST’);
    $http->addParam(‘email’ , ‘myemail’);
    $http->addParam(‘pass’ , ‘mypassword’);
    $http->setReferrer(‘http://facebook.com/‘);
    $http->execute(‘https://login.facebook.com/login.php‘);
    echo ($http->error) ? $http->error : $http->result;
    ?>

    Any solution would be very nice!

  45. 8/10/2011Jannik says:

    include_once(‘class.http.php’);
    $http = new Http();
    $http->setMethod(‘POST’);
    $http->addParam(‘email’ , ‘sry);
    $http->addParam(‘pass’ , ‘bla’);
    $http->setReferrer(‘http://facebook.com/‘);
    $http->execute(‘https://login.facebook.com/login.php‘);
    echo ($http->error) ? $http->error : $http->result;

    sorry, code wasnt submitted correctly, here you …

Write a comment: