Khriz
Khriz

Reputation: 5998

PHP cURL timeout in redirections

I was testing the 303 redirection in PHP for a use case in one of my company websites and I noticed a huge delay between 2 different cases, one execution was normal and the other lasted 10 seconds, I realized that was the timeout I set (with the CURLOPT_TIMEOUT flag).

The test was to try the case where a POST query transforms into a GET query after a redirection.

I tested it with 301 and 302 redirections also and the result was the same. Finally after struggling a lot with this issue I found the solution and I thought it'd be interesting to share.

Redirect page

<?php

header("HTTP/1.1 303 See Other");    
header("Location: http://127.0.0.1/test-303-redirection-2.html");

cURL example script

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1/test-303-redirection-1.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=value1&field2=value2");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'host: 127.0.0.1',
    'accept: */*',
    'content-length: 29',
    'content-type: application/x-www-form-urlencoded'
    )
);

$theResponse  = curl_exec($ch);

print_r(curl_getinfo($ch)) ;

This script lasted 10 seconds every time it was executed.

Upvotes: 0

Views: 1317

Answers (1)

Khriz
Khriz

Reputation: 5998

The bug was in our cURL wrapper class, it add the content-length header using the POST fields length. That made headers were sent like this:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'host: 127.0.0.1',
    'accept: */*',
    'content-length: 29',
    'content-type: application/x-www-form-urlencoded'
    )
);

Just removing the content-length header from the array removed the timeout and the execution was smooth as it should be. I hope this helps someone

Upvotes: 2

Related Questions