1252748
1252748

Reputation: 15372

How can PHP test if a given URL returns a 403 error

How can I test whether a given URL is a 403 error?

define('HTTP_STATUS', 403);
echo var_dump(http_response_code("badURL.com"));

and

 var_dump(http_response_code("bad_url.com"));

have not worked for me

Upvotes: 0

Views: 3044

Answers (3)

Havenard
Havenard

Reputation: 27854

You can use cURL:

$curl = curl_init('http://badurl.com/');
curl_setopt_array($curl, array(
   CURLOPT_NOBODY         => true, // use HEAD method, no body data
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_SSL_VERIFYPEER => false
));
curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE); 

Upvotes: 2

MatsLindh
MatsLindh

Reputation: 52802

http_response_code is for setting or retrieving the response status sent back to the client invoking your PHP script, it is not for making requests out to other services located somewhere on the Internet.

You can use file_get_contents to make a request to another service, then use $http_response_header to get the headers (including the HTTP response code).

function get_response_code($url) {
    @file_get_contents($url);
    list($version, $status, $text) = explode(' ', $http_response_header[0], 3);

    return $status;
}

var_dump(get_response_code('http://badurl.com'));

This will also support all forms of URLs that file_get_contents support, including HTTPS (if compiled with SSL support).

If you want to perform a ´HEAD` request instead, to avoid having to potentially download any content (.. but which may have its own issues, where it might not return the same error code), you can either use cURL or a custom HTTP verb with file_get_contents:

file_get_contents($url,
    false, 
    stream_context_create(array(
        'http' => array(
            'method' => 'HEAD' 
        )
    )
);

Or using cURL instead:

$ch = curl_init($url);

// if you want to issue a HEAD request instead, uncomment the following
// updated from Havenard's comment - you might also want to set
// CURLOPT_SSL_VERIFYPEER to false if you don't want to verify SSL certificates.
// curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

return status;

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Not like that, certainly.

Try actually getting it:

$fp = fsockopen("badURL.com",80,$errno,$errstr,1); // 1 second timeout to prevent lag
if( !$fp) echo "Failed to connect! ".$errno." ".$errstr;
else {
    fputs($fp,"HEAD / HTTP/1.0\r\nHost: badURL.com\r\n\r\n");
    $line = fgets($fp); // get first line
    fclose($fp); // not interested in the rest
    list($version,$status,$statusText) = explode(" ",$line,3);
    var_dump($status);
}

Upvotes: 0

Related Questions