PHP get_headers () alternative

I need a PHP script that reads the HTTP response code for each URL request.

sort of

$headers = get_headers($theURL);
return substr($headers[0], 9, 3);

The problem is that the get_headers () function is disabled at the server level, as a policy. So it does not work.

The question is, how do I get the HTTP response code for the url?

+5
source share
3 answers

If cURL is enabled, you can use it to get the whole header or just the response code. The following code assigns the response code to a variable $response_code:

$curl = curl_init();
curl_setopt_array( $curl, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => 'http://stackoverflow.com' ) );
curl_exec( $curl );
$response_code = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
curl_close( $curl );

To get the whole header, you can send a HEAD request, for example:

$curl = curl_init();
curl_setopt_array( $curl, array(
    CURLOPT_HEADER => true,
    CURLOPT_NOBODY => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => 'http://stackoverflow.com' ) );
$headers = explode( "\n", curl_exec( $curl ) );
curl_close( $curl );
+10
source

HttpRequest, : http://de2.php.net/manual/en/class.httprequest.php

$request = new HttpRequest("http://www.example.com/");
$request->send();
echo $request->getResponseCode();

: http://de2.php.net/manual/en/function.fsockopen.php

$errno = 0;
$errstr = "";

$res = fsockopen('www.example.com', 80, $errno, $errstr);

$request = "GET / HTTP/1.1\r\n";
$request .= "Host: www.example.com\r\n";
$request .= "Connection: Close\r\n\r\n";

fwrite($res, $request);

$head = "";

while(!feof($res)) {
    $head .= fgets($res);
}

$firstLine = reset(explode("\n", $head));
$matches = array();
preg_match("/[0-9]{3}/", $firstLine, $matches);
var_dump($matches[0]);

Curl , - ;)

+4

You can create and read your own HTTP requests using fsockopen and regular file operations. Check out my previous answer on this topic:

Are there any other options for holiday clients besides CURL?

+3
source

All Articles