PHP’s HttpRequest object – delayed and fragmented requests

Having trouble receiving HTTP requests made by PHP’s HttpRequest object? Well I did… A HTTP request made by a proxy service written in PHP was being send to a Web-Interface-Server written in QT, and it mostly worked fine, but every now and then, and almost always with large requests (with lots of POST parameter data) it became laggy, and lasted for 2 seconds without any good reason.

The problem appeared to be that the request came in two parts, and the second part was send about 2 seconds after the first one. After a colleague of mine point out a solution to this same problem when using curl, I fixed the problem with the HttpRequest in the same manner.

Curl solution:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

HttpRequest equivalent:

$r->setOptions
(
    array
    (
        'headers' => array('Expect:' => ''),    // send the request as a whole
    )
);

What does this actually mean? Well, when making a request, either by curl or by HttpRequest object, by default, header contains “Expect: 100″ parameter, meaning that the server should return HTTP code 100 before receiving the other part of the request. As this wasn’t the case on our server, we had slow and delayed HTTP requests (and I wonder why there was any in the first place). By removing or at least modifying the Expect parameter to have no value rather than 100, we fixed the issue. I hope this helps you out…

Whole request code:

$r = new HttpRequest($requestUrl, HttpRequest::METH_POST);

// configure the request options
$r->setOptions
(
    array
    (
        'headers' => array('Expect:' => ''),    // remove the expect parameter
    )
);

$r->addPostFields(array('proxy' => 'proxy'));    // add some post parameters

try
{
    // make the request
    $r->send();

    // check the return code and render contents or an error message
    if ($r->getResponseCode() == 200)
    {
        $responseBody = $r->getResponseBody();

        echo $responseBody;
        die();
    }
    else
    {
        // handle this yourself
    }
}
catch (HttpException $ex)
{
    // handle this yourself
}

About Miljenko Barbir

Miljenko Barbir is a software (and web) developer/web designer from Split, Croatia. Started out with C#, ASP.Net, and SQL Server, but in the last few years he has "moved on" to PHP and MySQL, loving CakePHP, jQuery, RegEx for obvious reasons, making our lives easier. Currently working for a local company in Split, but he's also available for freelance work.
This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>