Grab IP Address With a small php script

Introduction

In this tutorial, I’ll be showing you how to grab someone’s IP address using PHP. Unlike most tutorials, I’ll be showing you what each part of the code means!
The Simple Way

This PHP code will simply print the visitor’s IP address onto the page.

PHP Code:
<?php
print ($_SERVER['REMOTE_ADDR']; //prints the IP on the page (Obviously)
?>

Printing The Visitor’s IP Address To A File

PHP Code:
<?php
$ip = $_SERVER['REMOTE_ADDR']; //sets the visitors IP ($_SERVER['REMOTE_ADDR']) to the variable "$ip"
$handle = fopen('ipaddresses.txt', 'a+'); //opens ipaddresses.txt for reading and writing (MUST HAVE FILE NAMED ipaddresses.txt)
fwrite($handle, "{$ip}\n");  //writes the IP address to ipaddresses.txt
fclose($handle); //closes ipaddresses.txt for reading and writing
?>

Putting Your Code Into A Index.php File

PHP Code:
<?php
<html>
<?php
$file = "ipaddresses.txt"; //turns the text file into a variable
$f=fopen($file, 'a+'); //opens up the text file for reading and writing
fwrite($f,$_SERVER['REMOTE_ADDR']."\n"); //writes the IP address to ipaddresses.txt
fclose($f); //closes ipaddresses.txt for reading and writing
?>
<h1>File Not Found</h1>
</body>
</html> 

Comments

comments