views:

23

answers:

2

This bug has given my hours of anguish. This is a simplified version of what I'm doing:

[01] $h = get_headers($url, 1);
[02] $resp_code = $h[0];
[03] $resp_code = strtolower($resp_code);
[04] $resp_code = str_replace(' ','',$resp_code);
[05] echo 'just before going in. $resp_code = ' . $resp_code . '<br/>';
[06] switch ($resp_code) {
[07]   case 'http/1.1200ok':
[08]     echo '200';
[09]     break;
[10]   case 'http/1.0301movedpermanently':
[11]     echo '301';
[12]     break;
[13]   case 'http/1.0302movedtemporarily':
[14]     echo '302';
[15]     break;
[16]   case 'http/1.0404notfound':
[17]     echo '404';
[18] }
[19] echo 'just got out.';

The output I get. trying different urls, is different, for some urls it works correctly and for some it does not output any response code at all! Even though from the what echo shows on line 5 you expect one of the cases should be entered, it does not, and the next output comes from line 19.

You might wonder why I have converted the response codes to all lower, and stripped spaces, that was done as an attempt to factor out any minor differences there might be between text sent by different servers. I'm not aware if that could happen or not, it was done just in case and out of dismay :(

Could it be character encoding related? inflation/deflation? a bug in PHP? a virus on my system?

Any help would be greatly appreciated.

+2  A: 

The last three headers are with http/1.0. So no case will be matched if it is a 1.1 server and it doesn't return 200.

Maybe you should try:

$h = get_headers($url, 1);
$h = explode(' ', $h[0]);
$responseCode = $h[1];

switch ($responseCode) {
    case '200':
    // ...
}
nikic
Thanks really. I will try it and post back the result.
Majid
It did it! Though I'm still shocked the seemingly simple method I originally used fails intermittently. So, I guess it has been a result of some servers returning http/1.0 as you pointed first.
Majid
A: 

use $_SERVER['SERVER_PROTOCOL'] as the basis for checking HTTP protocol version

stillstanding
Thanks, but here I'm trying to check if the url returns a 200, 301, 302, or 404. But as nikic pointed, apparently wrong protocol numbers get in the way of a full string match. So your suggestion could be used to parse the correct long header section, but the solution nikic suggested works like charm.
Majid