Open In App

How to identify server IP address in PHP ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

What is an IP Address ? IP Address or Internet Protocol Address is a numerical value assigned to every device on network which 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 that 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 that contains the information regarding the headers, paths and script locations. The web server itself creates the entries of this array. Though it does not guarantee every web server will provide the contents of these arrays, servers may usually omit some of the $_SERVER array contents.
In order to obtain the IP address of the server one can use [‘SERVER_ADDR’], it returns the IP address of the server under the current script is executing.

Another method is using the [‘REMOTE_ADDR’] in the $_SERVER array. [‘REMOTE_ADDR’] is only used for getting the IP address for the local servers although the output produced will be the same as using [‘SERVER_ADDR’] for the local server IP address.

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




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



Last Updated : 01 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads