How to get the client IP address in PHP ?

0 votes
I want to keep record of the user who logged into my website through his/her IP address.

How can I get the client IP address using PHP?
Apr 8 in PHP by kartik
• 20,980 points
794 views

1 answer to this question.

0 votes

Hello,

Here is a code sample of a good way to get the IP address of the user.

$ip = $_SERVER['HTTP_CLIENT_IP'] ? $_SERVER['HTTP_CLIENT_IP'] : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);

Here is a shorter version that uses the elvis operator:

$_SERVER['HTTP_CLIENT_IP'] ? : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? : $_SERVER['REMOTE_ADDR']);

Here is a version that uses isset to remove notices:

$ip = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];

Thank You!!

answered Apr 8 by Niroj
• 44,800 points

Related Questions In PHP

0 votes
1 answer

How to merge two arrays while keeping keys instead of reindexing in php?

Hello, Considering that you have $replaced = array('1' => ...READ MORE

answered Apr 1 in PHP by Niroj
• 44,800 points
63 views
0 votes
0 answers
0 votes
1 answer

How can I handle the warning of file_get_contents() function in PHP?

Hello @kartik, This is fairly simple: if (!$data = ...READ MORE

answered Apr 7 in PHP by Niroj
• 44,800 points
272 views
0 votes
1 answer

How can I get ID of the last updated row in MySQL?

Hello @kartik, Suppose, item_id is an integer identity column in items table ...READ MORE

answered Apr 9 in PHP by Niroj
• 44,800 points
214 views
0 votes
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 44,800 points
1,391 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 44,800 points
125 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 44,800 points
131 views
0 votes
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 44,800 points
1,355 views
0 votes
1 answer

How to get the current plugin directory in WordPress?

Hello @kartik, This will actually get the result ...READ MORE

answered May 8 in PHP by Niroj
• 44,800 points
104 views
0 votes
1 answer

How to retrieve or obtain data from the MySQL database using PHP?

Hello kartik,  Actually there are many functions that  ...READ MORE

answered Mar 27 in PHP by Niroj
• 44,800 points
60 views