Php get http request status

Two PHP Functions to Check HTTP Response Code (Status) of a URL using Curl

We can use the following PHP function to send a request to the URL and get its HTTP status code.

 if (!function_exists("get_http_code"))  function get_http_code($url)  $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($handle); $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); curl_close($handle); return $httpCode; > >

It is based on the CURL library – which you can install using:

 echo get_http_code("https://helloacm.com"); // print 200 ?>

Another implementation is to shell execute (basically run/shell_exec the command curl in the shell e.g. /bin/bash). The -I means to retrieve the HTTP Headers only, and the -s means to disregard other meta information. Then we just have to extract the first line of the headers e.g. “HTTP/2 200”

if (!function_exists("get_http_code"))  function get_http_code($url)  $cmd = trim(shell_exec("curl -s -I \"$url\" | head -1")); list($http, $code) = explode(" ", $cmd); echo "$http and $code\n"; return (int)$code; > >
if (!function_exists("get_http_code")) < function get_http_code($url) < $cmd = trim(shell_exec("curl -s -I \"$url\" | head -1")); list($http, $code) = explode(" ", $cmd); echo "$http and $code\n"; return (int)$code; >>

PHP Function to Post to Twitter In order to post twits to Twitter using Twitter APIs, you would first need to…

Steem Reputation Format Function in PHP On Steem Blockchain, the reputation can be formatted in a logarithmetic (base 10) scale. Given…

CloudFlare Blocks Suspicious URL I have set the security level to high and the cloudflare will block suspicious URL,…

How to Mask Email Addresses using PHP Function? For users privacy we don’t want to display the full email addresses — and we…

Filter out Spam Words using PHP Function Many situations we want to be able to detect if a post/comment is spam by…

Left and Right Function in PHP We all know in Visual Basic or VBScript (including VBA i.e. Visual Basic for Application,…

A Simple PHP Function to Disable Google Fonts in WordPress Google Fonts are sometimes heavy-weight and slow to load especially in some regions e.g. mainland…

Simple PHP Function to Display Daily Bing WallPaper Bing uploads a daily wallpaper, and we can show today’s Bing wallpaper via the following…

How to Truncate a String in PHP? The following is a PHP Function that allows us to truncate a string (and optionally…

How to Get Host Root Domain URL in PHP? Suppose you have two or more domains that have image-copies of the same websites, and…

Источник

curl_getinfo

// Check HTTP status code
if (! curl_errno ( $ch )) switch ( $http_code = curl_getinfo ( $ch , CURLINFO_HTTP_CODE )) case 200 : # OK
break;
default:
echo ‘Unexpected HTTP code: ‘ , $http_code , «\n» ;
>
>

// Close handle
curl_close ( $ch );
?>

Notes

Note:

Information gathered by this function is kept if the handle is re-used. This means that unless a statistic is overridden internally by this function, the previous info is returned.

User Contributed Notes 13 notes

Here are the response codes ready for pasting in an ini-style file. Can be used to provide more descriptive message, corresponding to ‘http_code’ index of the arrray returned by curl_getinfo().
These are taken from the W3 consortium HTTP/1.1: Status Code Definitions, found at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

[Informational 1xx]100=»Continue»
101=»Switching Protocols» [Successful 2xx]200=»OK»
201=»Created»
202=»Accepted»
203=»Non-Authoritative Information»
204=»No Content»
205=»Reset Content»
206=»Partial Content» [Redirection 3xx]300=»Multiple Choices»
301=»Moved Permanently»
302=»Found»
303=»See Other»
304=»Not Modified»
305=»Use Proxy»
306=»(Unused)»
307=»Temporary Redirect» [Client Error 4xx]400=»Bad Request»
401=»Unauthorized»
402=»Payment Required»
403=»Forbidden»
404=»Not Found»
405=»Method Not Allowed»
406=»Not Acceptable»
407=»Proxy Authentication Required»
408=»Request Timeout»
409=»Conflict»
410=»Gone»
411=»Length Required»
412=»Precondition Failed»
413=»Request Entity Too Large»
414=»Request-URI Too Long»
415=»Unsupported Media Type»
416=»Requested Range Not Satisfiable»
417=»Expectation Failed» [Server Error 5xx]500=»Internal Server Error»
501=»Not Implemented»
502=»Bad Gateway»
503=»Service Unavailable»
504=»Gateway Timeout»
505=»HTTP Version Not Supported»

And an example usage:
$ch = curl_init (); // create cURL handle (ch)
if (! $ch ) die( «Couldn’t initialize a cURL handle» );
>
// set some cURL options
$ret = curl_setopt ( $ch , CURLOPT_URL , «http://mail.yahoo.com» );
$ret = curl_setopt ( $ch , CURLOPT_HEADER , 1 );
$ret = curl_setopt ( $ch , CURLOPT_FOLLOWLOCATION , 1 );
$ret = curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , 0 );
$ret = curl_setopt ( $ch , CURLOPT_TIMEOUT , 30 );

// execute
$ret = curl_exec ( $ch );

if (empty( $ret )) // some kind of an error happened
die( curl_error ( $ch ));
curl_close ( $ch ); // close cURL handler
> else $info = curl_getinfo ( $ch );
curl_close ( $ch ); // close cURL handler

if (empty( $info [ ‘http_code’ ])) die( «No HTTP code was returned» );
> else // load the HTTP codes
$http_codes = parse_ini_file ( «path/to/the/ini/file/I/pasted/above» );

// echo results
echo «The server responded:
» ;
echo $info [ ‘http_code’ ] . » » . $http_codes [ $info [ ‘http_code’ ]];
>

Источник

PHP – Get HTTP Response Status Code From a URL

This post shows you how to get the HTTP response status code from a URL. To do this, we will use get_headers built-in function, which returns an array with the headers in the HTTP response.

1. Exploring get_headers function

Let’s create a test to check what response headers we will get.

$url = 'https://bytenota.com'; $responseHeaders = get_headers($url, 1); print_r($responseHeaders); 
Array ( [0] => HTTP/1.0 200 OK [Content-Type] => text/html; charset=UTF-8 [Link] => ; rel="https://api.w.org/" [Date] => Tue, 19 Jun 2018 07:42:10 GMT [Accept-Ranges] => bytes [Server] => LiteSpeed [Alt-Svc] => quic=":443"; ma=2592000; v="35,37,38,39" [Connection] => close ) 

As you can see in the result, the HTTP response status code is in the first index value of the array ( HTTP/1.0 200 OK ).

The response status code can be:

  • HTTP/1.0 200 OK:
  • HTTP/1.0 301 Moved Permanently
  • HTTP/1.0 400 Bad Request
  • HTTP/1.0 404 Not Found
  • ect.

You can find the full list of response status code on this page.

2. Implementation

function getHTTPResponseStatusCode($url) < $status = null; $headers = @get_headers($url, 1); if (is_array($headers)) < $status = substr($headers[0], 9); >return $status; > 

In the above code, we have implemented the function that returns an HTTP response status code only from given URL, i.e. we have removed HTTP/1.0 string in the first index value of the array.

3. Usage

The below are two examples showing how to use the implemented function.

$url = 'https://bytenota.com'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode; 
$url = 'https://google.com/this-is-a-test'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode; 

Источник

How to get the Status Code from HTTP Response Headers in PHP

We’ll see how to get the Status Code of any HTTP RESPONSE Headers sent by the server upon a HTTP REQUEST in PHP. For example, opening a webpage in a browser will send a HTTP request to the server and which in turn will be returned by a response. At times, we want to get the status code alone from the headers sent by the server for processing.

status-code-http-request-response-headers-php

Get the HTTP Response Status Code

First use the PHP get_headers() function to fetch the array of all the headers sent by the server and then strip the status code from it.

 $statusCode = get_response_code('http://example.com'); echo $statusCode; ?>

I hope you find this php tutorial useful.

1 comment:

Contact Form

Subscribe

You May Also Like

Like Us on Facebook

Categories

Affiliate Disclosure: This website is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon(.com, .in etc) and any other website that may be affiliated with Amazon Service LLC Associates Program.

Kodingmadesimple.com uses affiliate links to online merchants and receives compensation for referred sales of some or all mentioned products but does not affect prices of the product. All prices displayed on this site are subject to change without notice. Although we do our best to keep all links up to date and valid on a daily basis, we cannot guarantee the accuracy of links and special offers displayed.

Источник

Читайте также:  Css clearing all styles
Оцените статью