in_array is always false

0

I have this code to get the availability of any URL, but when using in_array () , whenever I compare it gives me a result of FALSE. I would like to know what I am doing wrong or is in terms of the type of variable treatment.

$headers = get_headers('http://www.example.com/');

//print_r(sscanf( $headers[0], 'HTTP/%*d.%*d %d'));
$accept = array( 200, 301, 302 );
if(in_array($headers[0], $accept)){
    echo "Disponible";
} else {
    echo "No disponible";
}
    
asked by Thephoenix25 25.05.2018 в 03:58
source

1 answer

0

According to the Manual, the get_headers information comes as follows:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

As you can see, the status code comes with other data: HTTP/1.1 200 OK for code 200 .

Therefore, your code will never work.

This can be resolved in several ways.

The simplest would be using cURL .

Something like this:

$url="http://www.example.com";
$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($handle);

$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$accept = array( 200, 301, 302 );
if(in_array($responseCode, $accept)){
    echo "Disponible";
} else {
    echo "No disponible";
}

curl_close($handle);

If it were the url of the script itself, you can get the response code with the use of http_response_code() .

Another option would be to extract the code using regular expressions. But we should see if the answers are all standard.

And another option would be to do a partial search of the values of your array in the key [0] of the header. In other words, look for values such as HTTP/1.1 200 OK * that contain the value 200 or 301 or 302 .

    
answered by 25.05.2018 / 05:50
source