How can I detect if the user is on localhost in PHP?
You can use the $_SERVER['HTTP_HOST']
variable to detect if the user is on localhost in PHP. This variable contains the host name of the server that the script is running on.
You can check if the host name is "localhost" or "127.0.0.1" as follows:
<?php
if ($_SERVER['HTTP_HOST'] == 'localhost' || $_SERVER['HTTP_HOST'] == '127.0.0.1') {
echo 'You are accessing the website from localhost.';
} else {
echo 'You are NOT accessing the website from localhost.';
}
?>
Watch a video course
Learn object oriented PHP
Another way to check if the user is on localhost is to use the gethostname()
function.
<?php
if (gethostname() === 'localhost') {
echo 'You are accessing the website from localhost.';
} else {
echo 'You are NOT accessing the website from localhost.';
}
?>
It's worth noting that $_SERVER['HTTP_HOST']
is less reliable than gethostname()
because it can be easily spoofed by the client.