Find IP Address in PHP


Find IP Address in PHP

Here now learn the script of to find ip address in php of visitor which visit on website.

To store Visitor ip addres in PHP has syntax :-

1
$_SERVER[‘REMOTE_ADDR’]     // return visitor ip address
When a ip address has been received then now need text file to enter in it by using the
 syntax fwrite() function

$myipaddress = $_SERVER['REMOTE_ADDR']."\r\n";
In above codes first declare a variable which can pick IP address of  Visitor. One thing remember if you are testing or working on localhost server then naturally it return Local IP 127.0.0.1
First, we will use a variable to store the ip address. If you are working on a localhost environment, it will return 127.0.0.1
1
$myipaddress = $_SERVER['REMOTE_ADDR']."\r\n";
Now time to store visitor IP address in file using the PHP functions fopen() and fwrite(). 
Use below codes for that :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// store visitor ip address
$myipaddress = $_SERVER['REMOTE_ADDR']."\r\n";

// Log file name which store all ip address
$ipfile = 'logdata.txt';

// store visitor data by opening log file
$ipfp = fopen($ipfile, 'a');

fwrite($ipfp, $myipaddress);

fclose($ipfp);
These codes produce the output like as below in our log file:

127.0.0.1
127.0.0.1
127.0.0.1
127.0.0.1
We can also approve more this script with help of to enter other PHP funcations like as browser information and visitor’s visited page.
For that we need miner changes in our pre-written PHP script codes.
Use below codes for that :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// store visitor ip address
$myipaddress = $_SERVER['REMOTE_ADDR']."\r\n";

// visited page name
$page = $_SERVER['SCRIPT_NAME'];

// browser detail
$brow = $_SERVER['HTTP_USER_AGENT'];

// Log file name which store all ip address
$ipfile = 'logdata.txt';

// store visitor data by opening log file
$ipfp = fopen($ipfile, 'a');

fwrite($ipfp, $myipaddress);

fclose($ipfp);
These codes produce the output like as below in our log file:

127.0.0.1 - /product.html Mozilla 19.0 (Windows NT)
127.0.0.1 - /product.html Mozilla 19.0 (Windows NT)
127.0.0.1 - /product.html Mozilla 19.0 (Windows NT)
127.0.0.1 - /product.html Mozilla 19.0 (Windows NT)
Enjoy :) you have done!
Share: