php Programming Exercies

PHP Exercises: Get the client IP address

PHP : Exercise-5 with Solution

Write a PHP script to get the client IP address.

IP address: An Internet Protocol address (IP address) is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing.

Internet Protocol version 4 (IPv4) defines an IP address as a 32-bit number. However, because of the growth of the Internet and the depletion of available IPv4 addresses, a new version of IP (IPv6), using 128 bits for the IP address, was developed in 1995, and standardized in December 1998. In July 2017, a final definition of the protocol was published. IPv6 deployment has been ongoing since the mid-2000s.

IP addresses are usually written and displayed in human-readable notations, such as in IPv4, and 2001:db8:0:1234:0:567:8:1 in IPv6. The size of the routing prefix of the address is designated in CIDR notation by suffixing the address with the number of significant bits, e.g.,, which is equivalent to the historically used subnet mask

The IP address space is managed globally by the Internet Assigned Numbers Authority (IANA), and by five regional Internet registries. They are responsible in their designated territories for assignment to end users and local Internet registries, such as Internet service providers. IPv4 addresses have been distributed by IANA to the RIRs in blocks of approximately 16.8 million addresses each. Each ISP or private network administrator assigns an IP address to each device connected to its network.

Sample Solution: -

PHP Code:

//whether ip is from share internet
if (!empty($_SERVER['HTTP_CLIENT_IP']))   
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
//whether ip is from remote address
    $ip_address = $_SERVER['REMOTE_ADDR'];
echo $ip_address;

Sample Output:

View the output in the browser


Flowchart: Get the first element from an array

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Create a simple HTML form and accept the user name and display the name through PHP echo statement.
Next: Write a simple PHP browser detection script.

What is the difficulty level of this exercise?

New Content: Composer: Dependency manager for PHP, R Programming