HTTP Class for PHP (supports both cURL and fsockopen)

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)

Example 2 – Invoking Yahoo Term Extraction API

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

Example 4 – Getting a protected feed

  • You can add this function in Orchid framework. πŸ™‚

  • Yeah Omi bhai – i’ve already planned that πŸ™‚ Just not been able to log into the SVN lately πŸ™

  • Great job Emran vai. Finally you released this. πŸ™‚
    yea its a good idea if you add this to orchid framework. πŸ™‚

    cool man πŸ™‚

  • H2

    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.

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

  • Wow, It’s a nice theme. Tobe menu gula dekhte ekto asubidha hocche r ki πŸ™‚

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

  • Pingback: ASP mit Javascript einbinden? - jswelt - Forum (Javascript, PHP, MySQL, AJAX, Webdesign)()

  • Pingback:   New Addition - http object by Orchid()

  • Pingback: Weekend Links -- CSS & Multiple Background Images, Programming Book Profits, PHP HTTP Class, MooTools 1.2, IE8's New Meta Tag, and Domain Tasting()

  • 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.

  • @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 πŸ™‚

  • Pingback: Edmonds Commerce Blog()

  • cool work.

  • Pingback: HTTP Class for PHP | AplicacionesWeb()

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

  • @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!

  • Richard

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

  • 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

  • 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?

  • 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?

  • Vince

    It seems that fsockopen method doesn't follow redirects.

  • Vince

    It seems that fsockopen method doesn’t follow redirects.

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

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

  • Eydun

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

  • Eydun

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

  • pwb

    What's the point of cURL if fsockopen works?

  • pwb

    What’s the point of cURL if fsockopen works?

  • Rob

    Could you please show me an example of the usage of cookies inside this class?

    • Yes, it’s similar to how you add a param:
      $http->addCookie('logged_in_user' , '747');

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

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

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

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

  • Fixed. Thanks for noticing.

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

    $http->addCookie('logged_in_user' , '747');

  • The library supports both, so it's the choice of the dev πŸ™‚

  • 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.

  • 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.

  • sue

    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');
    $http->execute('https://www.test.com/suite/portal/index.jsp');

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

  • sue

    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’);
    $http->execute(‘https://www.test.com/suite/portal/index.jsp’);

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

    • 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.

  • Pingback: Antwort auf "$HTTP_USER_AGENT" mittels php emulieren - php.de()

  • 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.

  • 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.

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

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

  • 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.

  • Pingback: Custom login form (authentication) to Basecamp (using PHP, no cURL!, no OpenID) Β« DocuView - document management system()

  • MiniGod

    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.

  • MiniGod

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

  • Emran Hasan

    @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.

  • Pingback: Code Updates (HTTP class, Extended CodeIgniter Model, Cross-domain AJAX transport) | PHP Tutorials()

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

  • Plsnhat

    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(“rnrn”, $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 . “rn”;
    }

  • Plsnhat

    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))

  • Plsnhat

    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-urlencodedrn”;

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

  • Jannik

    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!

  • Jannik

    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 …

  • Hi Emraan, the download link is not working.