Check the HTTP Reponse Status Code of a Request in PHP
We can use the following PHP function to send a request to the URL and get its HTTP status code.
<?php
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:
apt install php-curl
Example usage:
<?php
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;
}
}
Online CURL: Simple CURL Utility/API
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - Maximum Product by Splitting Integer using Dynamic Programming or Greedy Algorithm
Next Post: Getting a List of Old Files in a Directory in Java by Comparing the Files Creation Time