W3docs

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.

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:

Example of checking if the host name is "localhost" or "127.0.0.1" in PHP

<?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.';
}
?>

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

Another way to check if the user is on localhost is to use the gethostname() function.

Example of using the gethostname() function to check if the host name is "localhost" or "127.0.0.1" in PHP

<?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.