Created
February 4, 2019 11:50
-
-
Save mkerstner/12b67767468bffce6010b6986e531d5e to your computer and use it in GitHub Desktop.
Simple PHP cURL HTTP status code checker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Tests and sets HTTP Header status code based on the response from the | |
* $urlToTest. | |
* | |
* Optionally waits $maxTimeout seconds and uses $defaultStatusCode in | |
* order to overwrite status code from $urlToTest. In addition, optionally | |
* $printStatusCode to response. | |
* | |
* @author Matthias Kerstner <matthias@kerstner.at> | |
* @version 1.0.0 | |
* @requires PHP 5.4+ with cURL enabled | |
*/ | |
// @var <INT> seconds to wait for completion. Set to 0 to disable | |
$maxTimeout = 10; | |
// @var <STRING> URL to test HTTP status code for | |
$urlToTest = 'https://www.yourdomain.com/'; | |
// @var <BOOL> whether to output the Status: ... message on return | |
$printStatusCode = true; | |
// @var <INT> default HTTP status code to return if anything runs not | |
// according to plan. Set to 0 to disable and use response from $urlToTest | |
// directly | |
$defaultStatusCode = 0; | |
// @var <BOOL> set to true to enable debugging for curl | |
$curlVerbose = false; | |
// ============================================================================ | |
// DO NOT EDIT BELOW THIS LINE | |
// ============================================================================ | |
set_time_limit($maxTimeout); | |
ob_start(); | |
$ch = curl_init($urlToTest); | |
curl_setopt($ch, CURLOPT_VERBOSE, $curlVerbose); | |
curl_setopt($ch, CURLOPT_HEADER, true); | |
curl_setopt($ch, CURLOPT_NOBODY, true); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); | |
curl_setopt($ch, CURLOPT_TIMEOUT, $maxTimeout); | |
$result = curl_exec($ch); | |
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
if ((int) $httpCode !== 200) { | |
$httpCode = $defaultStatusCode !== 0 ? $defaultStatusCode : $httpCode; | |
} | |
http_response_code($httpCode); | |
curl_close($ch); | |
ob_end_clean(); | |
if ($printStatusCode) { | |
die('Status: ' . $httpCode); | |
} |
$printStatusCode is never changed before it's checked.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$defaultStatusCode isn't changed from what it's set to before it's checked... so it'll always be 0 when it's checked.