<?php

define("HTTP_TIMEOUT", 1.0);

$curl_is_enabled = in_array('curl', get_loaded_extensions());

if(isset($_GET["action"]) && !empty($_GET["action"])) 
{
	$action = $_GET["action"];
	if ($action == 'isWebServerAvailable') 
    {
		$url = htmlentities(isset($_GET["query"]) ? $_GET["query"] : "");
			isWebServerAvailable($url);
	}
}

// cURL Unavailable -------------------------------------------------------------------------------
function PHP_get_http_response_code($url)
{
    set_error_handler
    (
        function ($severity, $message, $file, $line) 
        {
            // echo $message . "\n\n";
            throw new ErrorException($message, $severity, $severity, $file, $line);
        }
    );

    $http_response_code = 0;
    try
    {
        if (version_compare(PHP_VERSION, '7.1.0', '>=')) 
        {
            $context = array('http' => array('timeout' => HTTP_TIMEOUT));
            $resource = stream_context_create($context);
            $headers = get_headers($url, false, $resource);
        }
        else
        {
            $originalDefaults = stream_context_get_options(stream_context_get_default());
            stream_context_set_default(
                array('http' => array('timeout' => HTTP_TIMEOUT)));
            $headers = get_headers($url);
            stream_context_set_default($originalDefaults);
        }

        $http_response_code = substr($headers[0], 9, 3);
    }
    catch (Exception $e) { }

    restore_error_handler();

    return $http_response_code;
}    
// ------------------------------------------------------------------------------------------------

// cURL Available ---------------------------------------------------------------------------------
function cURL_get_http_response_code($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, true);          // We want the header
    curl_setopt($ch, CURLOPT_NOBODY, true);          // We don't need body
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, HTTP_TIMEOUT); // Set timeout to HTTP_TIMEOUT seconds
    curl_exec($ch);

    $http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    return $http_response_code;
}
// ------------------------------------------------------------------------------------------------

function isWebServerAvailable($url)
{
    $http_response_code = 0;
    
    global $curl_is_enabled;
    if ($curl_is_enabled)
        $http_response_code = cURL_get_http_response_code($url); 
    else
        $http_response_code = PHP_get_http_response_code($url);

    $server_available = ($http_response_code == 302 || $http_response_code == 200);
    
    echo json_encode(
        array(
            'status' => true,
            'result' => $server_available,
        )
    );
}

?>


