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

Example 2 – Invoking Yahoo Term Extraction API

1<?php
2
3include_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');
12echo ($http->error) ? $http->error : $http->result;

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

1<?php
2
3include_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
16echo ($http->error) ? $http->error : $http->result;

Example 4 – Getting a protected feed

1<?php
2
3include_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');
9echo ($http->error) ? $http->error : $http->result;

46 thoughts on “ HTTP Class for PHP (supports both cURL and fsockopen) ”

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

    cool man 🙂

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

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

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

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

  6. 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?

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

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

  9. 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;

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

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

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

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

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

  15. 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”;
    }

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

  17. 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!

  18. 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!

  19. 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 …

Comments are closed.