Auto Recognise Users via IP Address Through PHP/MySQLi

Language

Introduction: This tutorial will show you how to quickly identify your website users through their IP. Database: First we will need a database (mine is 'fln'), a table - 'test', and columns with data. My columns are; id, int, 5 length, primary key, auto increment username, varchar, 255 length ip, varchar, 255 length The IP field does not have to be 255 characters long but it will help to avoid errors in case we accidentally input some data other than an IP address. Connection: Now we need to connect to our database through PHP and MySQLi, we do this through a connection statement...
  1. <?php
  2. $con = mysqli_connect('localhost', 'root', '', 'fln'); //server, username, password, database name
  3. ?>
IP: Next we want to get the current visitor's IP address. We can do this through a simple Server variable 'Remote Address'. We store it in a string variable named 'ipaddr', standing for Internet Protocol Address...
  1. $ipaddr = $_SERVER['REMOTE_ADDR'];
Rows: Finally we want to check to see if there are any pre-existing rows containing our visitors IP, if so, we output their possible username. Otherwise we say that there is no username found in association with their IP address.
  1. $q = mysqli_query($con, "SELECT * FROM `test` WHERE `ip`='$ipaddr'");
  2. if (mysqli_num_rows($q) > 0) {
  3. echo 'Is your username ' . mysqli_fetch_array($q)['username'] . '?';
  4. }else
  5. echo 'No username found by that IP address!';
Important: IP addresses can be easily spoofed, so it is important not to use this as your only verification feature! You may also want to tell the users that their IP is being logged, for your own security reasons. Finished! All done! Next tutorial (I will link here when it's online) I will create the second part to this tutorial where we will allow any unrecognised users to register. You may download my test DB from the button below this post. Please note; the IP is '127.0.0.1' for anyone's localhost, this is because I used my localhost to test this - plus I wouldn't give out my IP...

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment