Trill Designs: Ip Location With Php - Trill Designs

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Ip Location With Php

#1 User is offline   Jaan Icon

  • Site Admin
  • Icon
  • Group: Administrators
  • Posts: 84
  • Joined: 23-November 09
  • LocationEstonia

Posted 25 January 2010 - 09:11 PM

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:

 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

<?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. ^^

Posted Image

checkip.php

<?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
0

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users