Detect if localhost/Xampp/Laragon is running

335 Views Asked by At

I am building a project where an online php script needs to loads files from the local server (this is not a public website).

Is it possible to detect if the local server is running or not and display a message. Something like this (C# Check If Xampp Server/Localhost is Running) but with php.

gethostbyname will not work.

$domain = '127.0.0.1/info.php'; // or $domain = 'localhost/info.php';
if (gethostbyname($domain) != $domain ) {
    echo 'Up and running';}
else {
    echo 'Run xampp first';
}

This will not work too

$file = '127.0.0.1/info.php';
$file_headers = @get_headers($file);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
    echo 'Run xampp first';
}
else {
    echo 'Up and running';
}
1

There are 1 best solutions below

5
Alex Howansky On

This is not a URL, it's a local filename:

$file = '127.0.0.1/info.php';

It lacks the leading protocol specifier, so it's looking for a file named info.php in a directory named 127.0.0.1.

You will need:

$file = 'http://127.0.0.1/info.php';

Then, assuming that http://127.0.0.1/info.php is a valid URL that will be served if the web service is running, you can use file_get_contents() to try and load the page. This will issue a warning and return false on failure.

if (@file_get_contents('http://127.0.0.1/info.php')) {
    echo "server is up";
} else {
    echo "server is down";
}

You could also use get_headers() as in your exmaple, but note that if you get a 404 Not Found, that still means the server is up and running.