0

This bug has given me 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.

Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127
  • get_headers has some flaw see: http://stackoverflow.com/questions/12781795/get-headers-inconsistency – Baba Oct 08 '12 at 15:33

2 Answers2

2

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
  • 100,734
  • 37
  • 191
  • 225
0

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

bcosca
  • 17,371
  • 5
  • 40
  • 51
  • 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 Fouladpour Sep 05 '10 at 14:26