Heeey people!

I was thinking.. I haven't posted any tutorials lately so I was thinking I could make something useful today.. I hope you like this tutorial and enjoy

First of all you must download IPs database: Download

Now it's time to insert it into our database. But first you must make a database:

Code:
 CREATE TABLE `ip`.`locations` (
`from` VARCHAR( 100 ) NOT NULL ,
`to` VARCHAR( 100 ) NOT NULL ,
`short` VARCHAR( 10 ) NOT NULL ,
`cc3` VARCHAR( 100 ) NOT NULL ,
`cname` VARCHAR( 100 ) NOT NULL
) ENGINE = InnoDB
Now let's create an import.php file.

import.php

Code:
<?php

// Connect to your database
$con = mysql_connect("localhost", "yourUsername", "yourPassword");

// Display an error if there was a problem with connection
if(!$con){
    
    die(mysql_error());
    
}

// Select your database
$select_db = mysql_select_db("ip", $con);

// If there was problems with selecting your database.. It will display an error
if(!$select_db){
    
    die(mysql_error());
    
}

// Select your database file
$db = file("ip-to-country.csv"); 

// Now let's get all rows separately and insert it into database
foreach($db as $row){ 
        
    $content = trim( str_replace('"', "'", str_replace("'", "\'", $row) ) ); 
    $sql = "INSERT INTO locations (from, to, short, cc3, cname) VALUES($content)"; 
    $query = mysql_query($sql);
        
    if(!$query){
            
        die(mysql_error());
            
            
    }
        
}

// If it's done.. Display this message
echo "Done!"; 

?>
Now our ip database is inserted into our SQL database. Now it's time to make simple script that will get us our location. ^^



checkip.php

Code:
<?php

// Let's start our function
function check_country($ip){ 
    
    // Connect to database
    $con = mysql_connect("localhost", "yourUsername", "yourPassword");
    
    if(!$con){
        
        die(mysql_error());
        
    }
    
    // Select database
    $select_db = mysql_select_db("ip", $con);
    
    if(!$select_db){
        
        die(mysql_error());
        
    }
   
    // Now let's get the long ip 
       $real_ip = ip2long($ip); 
    $sql = "SELECT cname, short FROM locations WHERE from <= '$real_ip' and to >= '$real_ip'"; 
    $sql = mysql_query($sql);
    $cd = mysql_fetch_assoc($sql); 
    
    $country = ucwords(strtolower($cd['cname']));
    $short = strtolower($cd['short']);
    
    // Let's display your user's ip and location
    echo "IP: $ip<br />";
    echo "Location: <img src='flags/$short.gif' /> $country<br />";
  
}

check_country($_SERVER['REMOTE_ADDR']);

?>
And it's done.. I hope it helped and you liked it.

Regards,
Jaan