Solved

Using IP address to determine language of welcome message upon login?

Posted on 2008-10-24
6
1,124 Views
Last Modified: 2012-08-13
I'm currently using wordpress on my site, and I have the "Sidebar Login" plugin activated so that users can login without having to navigate away from the actual site into the "wp-admin" area.

I have figured out a way to display "random" welcome messages to users when they login. These messages range from slang terms in english, to all kinds of different "hellos" in other languages. What I would LIKE to do is to somehow determine what country a user is visiting from by sniffing the IP address, then using that information to display a welcome message which corresponds to their native language.

Is this possible?

Keep in mind that I have absolutely no idea as to how to "sniff" an IP address, nor would I have any clue as to how to determine which country that particular IP is coming from.

I've included the entire sidebar-login plugin php file so that you can get an idea as to what the code looks like.
<?php
/*
Plugin Name: Sidebar Login
Plugin URI: http://wordpress.org/extend/plugins/sidebar-login/
Description: Adds a sidebar widget to let users login
Version: 2.1.2
Author: Mike Jolley
Author URI: http://blue-anvil.com
*/
 
 
 
function sidebarlogin() {
	$args["before_widget"]="";
	$args["after_widget"]="";
	$args["before_title"]="<h2 class=\"lightgray\">";
	$args["before_name"]="<span class=\"lightblue\">";
	$args["after_name"]="</span>";
	$args["after_title"]="</h2>";
	widget_sidebarlogin($args);
}
function widget_sidebarlogin($args) {
	
		extract($args);
		
		global $user_ID;
 
		if (isset($user_ID)) {
			// User is logged in
			//Begin random greetings when logged in
  $greets[] = 'Hello ';
  $greets[] = 'Welcome ';
  $greets[] = 'Howdy ';
  $greets[] = 'Bonjour ';
  $greets[] = 'Bueno ';
  $greets[] = 'Salut ';
  $greets[] = 'mArHAbAn ';
  $greets[] = 'Salam ';
  $greets[] = 'Konnichi Wa ';
  $greets[] = 'Shwmae ';
  $greets[] = 'Pryvit ';
  $greets[] = 'Guten Tag ';
  $greets[] = 'Your name is ';
  $greets[] = 'Howdy doo ';
  $greets[] = 'Ello ello ello ';
 
  srand ((double) microtime() * 1000000);
  $random_number = rand(0,count($greets)-1);
//End random greetings when logged in
			$user_info = get_userdata($user_ID);
			echo $before_widget . $before_title . __($greets[$random_number]) . $before_name . $user_info->user_login . $after_name . __("!") . $after_title;
			echo '<ul class="pagenav">
					<li class="page_item"><a href="'.get_bloginfo('wpurl').'/wp-admin/">'.__('Dashboard').'</a></li>
					<li class="page_item"><a href="'.get_bloginfo('wpurl').'/wp-admin/profile.php">'.__('Your Profile').'</a></li>
					<li class="page_item"><a href="'.current_url('logout').'">'.__('Logout?').'</a></li>
				</ul>';
		} else {
			// User is NOT logged in!!!
			echo $before_widget . $before_title . __("Please Login...") . $after_title;
			// Show any errors
			global $myerrors;
			$wp_error = new WP_Error();
			if ( !empty($myerrors) ) {
				$wp_error = $myerrors;
			}
			if ( $wp_error->get_error_code() ) {
				$errors = '';
				$messages = '';
				foreach ( $wp_error->get_error_codes() as $code ) {
					$severity = $wp_error->get_error_data($code);
					foreach ( $wp_error->get_error_messages($code) as $error ) {
						if ( 'message' == $severity )
							$messages .= '	' . $error . "<br />\n";
						else
							$errors .= '	' . $error . "<br />\n";
					}
				}
				if ( !empty($errors) )
					echo '<div id="login_error">' . apply_filters('login_errors', $errors) . "</div>\n";
				if ( !empty($messages) )
					echo '<p class="message">' . apply_filters('login_messages', $messages) . "</p>\n";
			}
			// login form
			echo '<form action="'.current_url().'" method="post" class="space25">';
			?>
			<p class="spacingfix"><label for="user_login"><?php _e('Username:') ?><br/><input name="log" value="<?php echo attribute_escape(stripslashes($_POST['log'])); ?>" class="sidelog" id="user_login" type="text" /></label></p>
			<p class="spacingfix"><label for="user_pass"><?php _e('Password:') ?><br/><input name="pwd" class="sidelog" id="user_pass" type="password" /></label></p>
			<p class="spacingfix"><label for="rememberme"><input name="rememberme" class="checkbox" id="rememberme" value="forever" type="checkbox" /> <?php _e('Remember me'); ?></label></p>
			<p class="submit"><input type="submit" name="wp-submit" id="wp-submit" value=" <?php _e('Do It!'); ?> " /><span class="omega left25"><input type="reset" name="wp-clear" id="wp-clear" value=" <?php _e('Fix It!'); ?> " /></span>
			<input type="hidden" name="sidebarlogin_posted" value="1" />
			<input type="hidden" name="testcookie" value="1" /></p>
			</form>
			<?php 			
			// Output other links
			echo '<ul class="sidebarlogin_otherlinks">';		
			if (get_option('users_can_register')) { 
				// MU FIX
				global $wpmu_version;
				if (empty($wpmu_version)) {
					?>
						
					<?php 
				} else {
					?>
					
					<?php 
				}
			}
			?>
			<li class="spacingfix"><a href="<?php bloginfo('wpurl'); ?>/wp-login.php?action=lostpassword" title="<?php _e('Please visit the Password Lost & Found to claim your password') ?>"><?php _e('Forget your password?') ?></a></li>
			<li class="spacingfix"><a href="<?php bloginfo('wpurl'); ?>/wp-signup.php"><?php _e('Register?') ?></a></li>
			</ul>
			<?php	
		}
		// echo widget closing tag
		echo $after_widget;
}
function widget_sidebarlogin_init() {
	if ( !function_exists('register_sidebar_widget') ) return;
	// Register widget for use
	register_sidebar_widget(array('Sidebar Login', 'widgets'), 'widget_sidebarlogin');
}
function widget_sidebarlogin_check() {
	if ($_POST['sidebarlogin_posted'] || $_GET['logout']) {
		// Includes
		//include_once('wp-settings.php');
		global $myerrors;
		$myerrors = new WP_Error();
		//Set a cookie now to see if they are supported by the browser.
		setcookie(TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN);
		if ( SITECOOKIEPATH != COOKIEPATH )
			setcookie(TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN);
		// Logout
		if ($_GET['logout']==true) {
			nocache_headers();
			wp_logout();
			wp_redirect(current_url('nologout'));
			exit();
		}
		// Are we doing a sidebar login action?
		if ($_POST['sidebarlogin_posted']) {
		
			if ( is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) )
				$secure_cookie = false;
			else
				$secure_cookie = '';
		
			$user = wp_signon('', $secure_cookie);
			
			// Error Handling
			if ( is_wp_error($user) ) {
			
				$errors = $user;
	
				// If cookies are disabled we can't log in even with a valid user+pass
				if ( isset($_POST['testcookie']) && empty($_COOKIE[TEST_COOKIE]) )
					$errors->add('test_cookie', __("<strong class=\"errtext\">ERROR:</strong> Cookies are blocked or not supported by your browser. You must <a href='http://www.google.com/cookies.html'>enable cookies</a> to use WordPress."));
					
				if ( empty($_POST['log']) && empty($_POST['pwd']) ) {
					$errors->add('empty_username', __('<div class="err"><strong class="errbold">ERROR:</strong> Please enter your username.</div>'));
					$errors->add('empty_password', __('<div class="err"><strong class="errbold">ERROR:</strong> Please enter your password.</div>'));
				}
					
				$myerrors = $errors;
						
			} else {
				wp_redirect(current_url('nologout'));
				exit;
			}
		}
	}
}
if ( !function_exists('current_url') ) :
function current_url($url = '') {
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") $pageURL .= "s";
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}
	if ($url == "logout" && strstr($pageURL,'logout')==false) {
		if (strstr($pageURL,'?')) {
			$pageURL .='&logout=true';
		} else {
			$pageURL .='?logout=true';
		}
	}
	if ($url == "nologout" && strstr($pageURL,'logout')==true) {
		$pageURL = str_replace('?logout=true','',$pageURL);
		$pageURL = str_replace('&logout=true','',$pageURL);
	}
	//added by mick 
	if (!strstr(get_bloginfo('wpurl'),'www.')) $pageURL = str_replace('www.','', $pageURL );
	//
	return $pageURL;
}
endif;
// Run code and init
add_action('init', 'widget_sidebarlogin_check',1);
add_action('widgets_init', 'widget_sidebarlogin_init');
?>

Open in new window

0
Comment
Question by:Eight7Teen
  • 3
  • 2
6 Comments
 
LVL 3

Expert Comment

by:raminhos
ID: 22801297
Checkout the attached class.

Not mine, didn't change the zip autor's file..

From http://www.phpclasses.org

There are two files name *.php.txt .. just rename it to *.php


countryfromip-2005-06-22.zip
0
 

Author Comment

by:Eight7Teen
ID: 22801408
Thanks for the reply, but that particular script requires the user to select their country from a list of possibilities generated from their IP address. I need something which will either explicitly define the country with corresponding welcome message, or at least use a "fall back" for each particular group of possibilities rather than needing user input.
0
 
LVL 3

Expert Comment

by:raminhos
ID: 22801452
I'm sorry to disapoint you my friend, but i just put the script work.. you didn't look at him at proper way..

Check example.php:

where is $ip = xxxxxxx....replace with: $ip = $_SERVER["REMOTE_ADDR"];

you can even use: $_SERVER["HTTP_ACCEPT_LANGUAGE"];

PS: Read the zip: READ_ME.txt
<?php
 
require_once('CountryFromIP.inc.php');
 
//$ip ='XXX.XXX.XXX.XXX';  // THIS IP IS FOR TEST...
 
// YOU CAN DO THIS:
$ip = $_SERVER["REMOTE_ADDR"];
 
$object = new CountryFromIP();
 
$countryName =  $object->GetCountryName($ip);
$flagPath =  $object->ReturnFlagPath();
 
echo "<BR> <B>Country: </B>".$countryName;
echo "<BR> <B>Flag: </B> <img src=".$flagPath." border='0'>";
?>

Open in new window

0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:Eight7Teen
ID: 22801556
I'm a PRE-noobie when it comes to php, so I'm sorry I didn't catch that.
I am assuming that if I were to want to display a greeting based on the country rather than the country name and a flag, I would need to use "if" statements to match up each language's greeting with the corresponding country?
0
 
LVL 3

Accepted Solution

by:
bogesman earned 500 total points
ID: 22801928
You can use maxminds GEOIP

Download binary format from here
http://www.maxmind.com/app/geolitecountry

The php API
http://www.maxmind.com/download/geoip/api/php/
Download
geoip.inc
Download sample and take a look
You can embed it in your code like this

if (isset($user_ID)) {
                        // User is logged in
                        //Begin random greetings when logged in
 
$ip = $_SERVER["REMOTE_ADDR"];
   include("geoip.inc");
$gi = geoip_open("/usr/local/share/GeoIP/GeoIPCity.dat",GEOIP_STANDARD);
$ccode = geoip_country_code_by_addr($gi, $ip);
geoip_close($gi);
 
 if ($ccode == "us") {
  $greets[] = 'Hello ';
  $greets[] = 'Welcome ';
  $greets[] = 'Howdy ';
}
if ($ccode == "fr") {
  $greets[] = 'Bonjour ';
}
  $greets[] = 'Bueno ';
  $greets[] = 'Salut ';
  $greets[] = 'mArHAbAn ';
  $greets[] = 'Salam ';
  $greets[] = 'Konnichi Wa ';
  $greets[] = 'Shwmae ';
  $greets[] = 'Pryvit ';
  $greets[] = 'Guten Tag ';
  $greets[] = 'Your name is ';
  $greets[] = 'Howdy doo ';
  $greets[] = 'Ello ello ello ';
 
  srand ((double) microtime() * 1000000);
  $random_number = rand(0,count($greets)-1);

Open in new window

0
 

Author Closing Comment

by:Eight7Teen
ID: 31509873
Thank you so much for giving me an example even I could understand. I really appreciate it. That seems fairly complex, but I think I understand the general concept behind it. Thanks again!
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
This article discusses how to create an extensible mechanism for linked drop downs.
The purpose of this video is to demonstrate how to integrate Mailchimp with WordPress, by placing a Mailchimp signup form on a WordPress Page or Post. This will be demonstrated using a Windows 8 PC. Mailchimp will be used. Log into your Mailchi…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question