How to get the IP address of a visitor in PHP?

Use $_SERVER["REMOTE_ADDR"]. It has the IP address of the client that connected to your server.

<?php
$ip = $_SERVER["REMOTE_ADDR"];

echo "Your IP: " . $ip;
?>

Output:

Sample output, yours will be different

Your IP: 203.0.113.25

If your website is behind a proxy, load balancer or a service like Cloudflare, REMOTE_ADDR shows the IP of that proxy. The real visitor IP is then sent in a header like HTTP_X_FORWARDED_FOR.

Note: Headers like X-Forwarded-For can be faked by the visitor. Trust them only when your own proxy sets them. Also remember that an IP address is personal data in some countries, so store it only when you need it.

Learn more about the similar topics:
Tutorials
PHP Forms Handling
PHP Send Mail
PHP header() Function
PHP mail() Function
Exercises & Assignments
Create a PHP Form with 2 fields Name and Hobbies
Interview Questions & Answers
What are the form method Attribute available for submitting?
How can we submit a form without a submit button?
What is the difference between GET and POST method in PHP?
How to redirect a page in PHP?
How to get the browser details of a visitor in PHP?
How to get the previous page (referrer) URL in PHP?
How to get the IP address of a visitor in PHP?