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.
1 2 3 4 5 6 7 8 9 10 11 | <?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; } } |
<?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:
1 | apt install php-curl |
apt install php-curl
Example usage:
1 2 3 | <?php echo get_http_code("https://helloacm.com"); // print 200 ?> |
<?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”
1 2 3 4 5 6 7 8 | 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; } }
Online CURL: Simple CURL Utility/API
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
319 wordsloading...
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