Open In App

How to Identify Server IP Address in PHP?

Last Updated : 23 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

What is an IP Address?

IP Address or Internet Protocol Address is a numerical value assigned to every device on the network that uses the Internet Protocol for Communication. An IP address serves two major functions:

  • Network/Host interface identification
  • Location addressing

Static IP addresses that do not change very often are provided to servers. The ISP provides a unique IP address to a home machine that is dialing via modem, and the IP address is unique for that session and it may change the next time for the machine.

How to identify your server's IP address?

  • The $_SERVER is an array in PHP containing information about headers, paths, and script locations.
  • The entries of the $_SERVER array are created by the web server.
  • Not every web server guarantees to provide all entries of the $_SERVER array; some contents may be omitted.
  • To obtain the server's IP address, the key $_SERVER['SERVER_ADDR'] is used. It returns the IP address of the server executing the current script.
  • Another method is using $_SERVER['REMOTE_ADDR'], which retrieves the IP address of the client (or the local server during local development).
  • For local servers, the result from $_SERVER['REMOTE_ADDR'] is often the same as that of $_SERVER['SERVER_ADDR'].

Example 1: This example identify the servers IP address using ['SERVER_ADDR'].

PHP
<?php

// PHP program to obtain IP address of
// the server

// Creating a variable to store the
// server address
$ip_server = $_SERVER['SERVER_ADDR'];

// Printing the stored address
echo "Server IP Address is: $ip_server";

?>

Output:

Server IP Address is: ::1

Example 2: This example identify the servers IP address using ['REMOTE_ADDR'].

PHP
<?php

// PHP program to obtain IP address of
// the server

// Create a variable to store the
// server ip address
$ip = $_SERVER['REMOTE_ADDR'];

// Printing the stored address
echo "IP Address is: $ip", "<br>";

?>

Output:

Server IP Address is: ::1

Note: If you try to run the above code on any online IDE it would either return a runtime error or no output, as private domains don't share their IP, try running on localhost or a server. For localhost, if ipv4 loopback address is used then it will give 127.0.0.1 and if ipv6 loopback address is used then it will give ::1.

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


Next Article

Similar Reads