look for ip address and change the language of the website - php

I want to know how can i add some script (javascript or maybe in PHP) to look for ip address and if ip is for sweden change the language of the website to Swedish , maybe change the location example.com/en to example.com/se or something like that ,
Thanks

You want do what's known as GeoLocation
You could do this with MaxMind's database and then process this in either your PHP app or as an Apache Module.
I'd advise that you recommend a language/locale option to users when they visit the site but ultimately allow them to override this.

Look at the browsers accept-language header first, then the browser identification string which might contain the OS language.
function getDefaultLanguage() {
if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
return parseDefaultLanguage($_SERVER["HTTP_ACCEPT_LANGUAGE"]);
else
return parseDefaultLanguage(NULL);
}
function parseDefaultLanguage($http_accept, $deflang = "en") {
if(isset($http_accept) && strlen($http_accept) > 1) {
# Split possible languages into array
$x = explode(",",$http_accept);
foreach ($x as $val) {
#check for q-value and create associative array. No q-value means 1 by rule
if(preg_match("/(.*);q=([0-1]{0,1}\.\d{0,4})/i",$val,$matches))
$lang[$matches[1]] = (float)$matches[2];
else
$lang[$val] = 1.0;
}
#return default language (highest q-value)
$qval = 0.0;
foreach ($lang as $key => $value) {
if ($value > $qval) {
$qval = (float)$value;
$deflang = $key;
}
}
}
return strtolower($deflang);
}

Not sure if it's a good idea or not, but heres how you'd do it:
$(function() {
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function(data) {
if (data.countryCode == 'SE') {
$('body').text('Välkommen till Sverige');
}else{
$('body').text("You're not Swedish ?");
}
});
});
FIDDLE
Without jQuery, I guess the easiest would just be:
<script type="text/javascript">
var lang = function(data) {
if (data.countryCode == 'SE') {
//swedish
} else {
//not swedish
}
}
</script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=lang"></script>​
or in PHP ?
<?php
$json = json_decode( file_get_contents('http://smart-ip.net/geoip-json') );
if ($json->countryCode == 'SE') {
//swedish
}else{
//not swedish
}
?>

Shortly, based on pure JavaScript, you can do...
<html>
<head>
<title>...</title>
<script language="JavaScript">
var lang = navigator.language || navigator.userLanguage;
//alert(lang);
if(lang == "en" || lang == "eng" || lang == "engs") {
window.location = "en/index.html"; //English
}
if(lang == "sv" || lang == "swe") {
window.location = "se/index.html"; //Swedish
}
</script>
</head>
<body>
</body>
</html>

Related

How do I code this the smart way, Ajax/PHP

I've got myself a little script that checks the validity of a link supplied by the user, making it safe to store in the database (safer at least) and to confirm it's a link to facebook.
Now I want to roll this code out for another links, changing parameters as and when needed so that links to people user profile on these sites work, bit I dont want to copy and paste the code another 5 times and then try and adapt the Ajax to work with it, if theres a better way to approach this.
This is my code, it can been seen working at www.vwrx_project.co.uk/test.php. It hopefully only accepts facebook.com/(something here) .
link_checker.php
<?php
function check_url($dirty_url) {
//remove anything before facebook.com using strstr()
//clean url leaving alphanumerics : / . only - required to remove facebook link format with /#!/
$clean_url = strstr(preg_replace('#[^a-z0-9:/.?=]#i', '', $dirty_url), 'facebook.com');
$parsed_url = parse_url("http://www.".$clean_url); //parse url to get brakedown of components
$safe_host = $parsed_url['host']; // safe host direct from parse_url
// str_replace to switch any // to a / inside the returned path - required due to preg_replace process above
$safe_path = str_replace("//", "/", ($parsed_url['path']));
if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] != '' && $parsed_url['path'] != '/') {
echo "Facebook";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '') {
echo "missing_profile1";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '/') {
echo "missing_profile2";
} else {
echo "invalid_url";
}
}
?>
Test.php
<?php
include_once ("includes/check_login_status.php");
include_once ("includes/link_checker.php");
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["L"])){
$dirty_url = $_POST["L"]; //user supplied link
//$dirty_url = "http://www.facebook.com/profile.php?id=4";
// if $dirty_url is blank
if($dirty_url == ""){
echo "no link supplied";
exit();
} else {
check_url($dirty_url);
}
exit();
}
?>
<html>
<head>
<title>testing</title>
<script type="text/javascript" src="js/main.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function cleanURL(){
var user_url = _("user_link").value;
var func = _("hidden").value;
if(user_url == ""){
_("status").innerHTML = "Please provide a link before clicking submit";
} else {
_("submitbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "test.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no link supplied"){
_("status").innerHTML = "Submitted blank form data.";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "invalid_url"){
_("status").innerHTML = "The url supplied is invalid";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile1"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile2"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else{
_("status").innerHTML = ajax.responseText;
}
}
}
ajax.send("L="+user_url);
}
}
</script>
</head>
<body>
<p id="status"></p>
<form id="linkform" onSubmit="return false;">
<input type="text" id="user_link">
<input type="hidden" id="hidden" value="Facebook">
<button id="submitbtn" onClick="cleanURL()">Submit</button>
</form>
Why dont you add an additional parameter which is the website you want to allow?
function check_url($dirty_url, $websiteURL)
Then update your function to use the $websiteURL variable instead of the hardcoded 'facebook.com'
Then when you want to have several different urls you can do this
check_url($dirty_url, 'facebook.com');
or
check_url($dirty_url, 'twitter.com');
Or are you wanting to be able to check for multiple sites in the single function? such as facebook.com and twitter.com

Separate url in autocomplete menu

I have an autocomplete jQuery menu, that output the name of all the users I have, from a MySQL database. I'm trying to link each selection to the proper profile. For that, the URL is something like: /profile.php?id=341, 341 that stands for the ID of the user selected.
The only problem, is that when I try to put the ID of a given user, ALL the ID of ALL the user are shown in the URL... and I want only the ID of the selected user!
I have tried with PHP, but I don't know what to add to the following line to make it work.
$req = mysql_query("select id, Username, EmailAddress from ***");
Should it be something like WHERE Username='username'....? Finally, I know that I should maybe try something else, without PHP, but I just want to test it that way! Thanks!
<input type="text" name="course" id="course" />
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#course").autocomplete("/test/test2.php", {
selectFirst: false,
formatItem: function(data, i, n, value) {
//make the suggestion look nice
return "<font color='#3399CC'>" + value.split("::")[0] + "</font>";
},
formatResult: function(data,value) {
//only show the suggestions and not the URLs in the list
return value.split("::")[0];
}
}).result(function(event, data, formatted) {
//redirect to the URL in the string
var pieces = formatted.split("::");
window.location.href = '/profile.php?id='+
<?php
mysql_connect ("***", "***","***") or die (mysql_error());
mysql_select_db ("***");
$req = mysql_query("select id, Username, EmailAddress from ***");
while($dnn = mysql_fetch_array($req))
{
echo $dnn['id'];
}
?>
;
console.log(data);
console.log(formatted);
});
});
</script>
Your MySQL query is true to every user in the database, so it returns all the users. If you want to go to "foo"'s profile, you need to tell the database to fetch "foo"'s id only. A unique row that the user has maybe there email and must be their username.
I assume you have an array in javascript which contains selected users:
var users = new Array("Daniel","Amy","Sandy");
then you need to use ajax to communicate to php:
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}//This can become an external file to link
</script>
so then you can post data to php:
<script>
var returnedStr = "";
function searchuser(){ //use searchuser function on a button to call
var usersStr = users.toString(); //the string that contain the users separated by ","
var ajax = ajaxObj("POST", "thisurl.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "fail"){ //i didn't include this in php, but you can add it yourself if you can't fetch from mysql
echo "Failed";
} else {
returnedStr = ajax.responseText;// when php echos
}
}
}
ajax.send("u="+usersStr);
}
</script>
then your php will need to handle the string:
<?php
if(isset($_POST["u"])){
$returnArr = array();
$returnStr = "";
$processedArr = explode(',', $_POST['u']); //Here the posted data will turn into an array
$lengthArr = count($processedArr);
for ($i=0; $i<=$lengthArr; $i++)
{
$req = mysql_query("SELECT id FROM xxx WHERE Username='$processedArr[$i]' LIMIT 1");
while($dnn = mysql_fetch_array($req))
{
array_push($returnArr, $dnn['id']);
}
}
$returnStr = implode(",",$returnArr);
echo ($returnStr);
}
?>
Now in Javascript returnedStr will hopefully be 1,2,3 or something like that.
Please comment if this doesn't work!

How to toggle external CSS on button click

I am facing one problem, I want to do something like this:
I want to toggle the EXTERNAL CSS when user is click on toggle button.
There are 5 different pages; there are:
Header
Footer
Main page
Contact us
About us
and I have 2 external style sheets:
style.css
style1.css
By default style.css is loaded.
Now when I click on toggle button then style1.css has to load, and when again click on toggle button style.css has to load and visa verse. I want to do something like this.
Is there anyone have an Idea regarding this. Please help me out!
CSS is loaded on header so when I click on toggle button I want to apply new style.css.
the problem i am facing is that when i am clicking on any other page at that time the default css is set but in my case i don't want that By default style.css is loaded now when user click on button style1.css is loaded now when user again click on button style.css is loaded when click again style1.css loaded and again style.css loaded i want to do something like this and this changes should be there for whole website of main! thnx for your valuable reply and wait for more accurate –
By doing something like this:
$("a").click(function () {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
See Applying stylesheets dynamically with jQuery
DEMO
See Stylesheet Switcher jQuery
<script src="script/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
if ($.cookie("css")) {
$("link").attr("href", $.cookie("css"));
}
$(document).ready(function () {
$("#nav li a").click(function () {
$("link").attr("href", $(this).attr('rel'));
$.cookie("css", $(this).attr('rel'), { expires: 365, path: '/' });
return false;
});
});
</script>
<ul id="nav">
<li>Original CSS</li>
<li>Larger Text</li>
<li>Something Different</li>
</ul>
try this
$("#btntoggle").click(function(){
if($("LINK[href*='style.css']").lenght() > 0){
$("LINK[href*='style.css']").remove();
addCss(path + "style1.css");
}else{
$("LINK[href*='style1.css']").remove();
addCss(path + "style.css");
}
});
function addCss(path){
var headID = $("head").get(0);
var newCss = document.createElement('LINK');
newCss.rel = 'StyleSheet';
newCss.type = 'text/css';
newCss.href= path;
newCss.media = 'screen';
headID.appendChild(newCss);
}
Note that i've added the default style sheet in the markup, in case the user got JS disabled. So you get some kind of a fallback.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style1.css">
<script type="text/javascript" src="../jquery-1.8.0.min.js"></script>
<script>
$(function(){
$("#change").click(function(){
$('head link').each(function(){
if($(this).attr('rel') == "stylesheet"){
if($(this).attr('href') == "style1.css"){
$(this).attr("href","style2.css");
} else {
$(this).attr("href","style1.css");
}
}
});
});
});
</script>
</head>
<body>
<button id="change">Change</button>
</body>
</html>
$url = Mage::helper("core/url")->getCurrentUrl(); // $url contain your current url
if(!isset($_SESSION['cssfile']) and !isset($_GET['l']))
{
/*$urlArr = explode("?",$url);
$tmpUrl = $urlArr[0];
$tmpUrl .= "?";
$andP = '';
$i=1;
for(;$i<count($urlArr);$i++)
{
$tmpUrl .= $andP.$urlArr[$i];
$andP = '&';
}
if($i>1)
$tmpUrl .= '&l=1';
else
$tmpUrl .= 'l=1';*/
//$urlGet = $tmpUrl;//$url."?l=0";
$_SESSION['cssfile'] = '1';
}
if(isset($_GET['l']) and $_GET['l']==0)
{
// $urlGet = $url."?l=1";
$_SESSION['cssfile'] = '0';
}
else if(isset($_GET['l']) and $_GET['l']==1)
{
// $urlGet = $url."?l=1";
$_SESSION['cssfile'] = '1';
}
if(isset($_SESSION['cssfile']))
{
$urlArr = explode("?",$url);
$tmpUrl = $urlArr[0];
$tmpUrl .= "?";
$andP = '';
$found = 0;
//for($i=1;$i<count($urlArr);$i++)
foreach($_GET as $key => $val)
{
if($key == 'l')
{
$found = 1;
if($val == 1)
$val = 0;
else
$val = 1;
}
$tmpUrl .= $andP.$key.'='.$val;
$andP = '&';
}
if($found == 0 && count($_GET)>0)
if($_SESSION['cssfile'] ==1)
$tmpUrl .= '&l=0';
else
$tmpUrl .= '&l=1';
else if($found == 0 && count($_GET)==0)
if($_SESSION['cssfile'] ==1)
$tmpUrl .= 'l=0';
else
$tmpUrl .= 'l=1';
$urlGet = $tmpUrl;
}
/*if(isset($_SESSION['cssfile']) and $_SESSION['cssfile'] == 'styles1.css' )
{
$_SESSION['cssfile'] = 'styles.css';
$_SESSION['cssfile']
}
else
{
$_SESSION['cssfile'] = 'styles1.css';
}*/
//echo '--'.$_SESSION['cssfile'];
if($_SESSION['cssfile'] ==1){
?>
<link href="<?php echo $this->getSkinUrl()?>css/styles1.css" rel="stylesheet" type="text/css" id="style" />
<?php }else{ ?>
<link href="<?php echo $this->getSkinUrl()?>css/styles.css" rel="stylesheet" type="text/css" id="style" />
<?php } ?>

PHP - how can I stop a function from printing an extra || at the end?

In PHP I have a function, the problem is it will output an extra || at the end that I dont want.
<script type="text/javascript">
function hide_card_code() {
var payment_source=document.getElementById('payment_source');
if(
<?
forEach($result_cards as $key => $value) {
echo "payment_source.value=='$value' || \n";
}
?>
) {
//do stuff...
return true;
}
}
</script>
It will output the following HTML. Note the extra || at the end.
<script type="text/javascript">
function hide_card_code() {
var payment_source=document.getElementById('payment_source');
if(
payment_source.value=='23' ||
payment_source.value=='24' ||
payment_source.value=='25' ||
) {
//do stuff...
return true;
}
}
</script>
How do I stop that extra || ?
No need for a loop! Just use json_encode to make a JavaScript array out of the values:
<script type="text/javascript">
function hide_card_code() {
var payment_source = document.getElementById('payment_source');
if(<?= json_encode(array_values($result_cards)) ?>.indexOf(payment_source.value) > -1) {
// do stuff...
return true;
}
}
</script>
$i=0;
forEach($result_cards as $key => $value) {
if($i == 0){
echo "payment_source.value=='$value' \n";
$i++;
}
else
echo " || payment_source.value=='$value' \n";
}
Why make things complicated, if there is a simple way? json_encode is slow, looping is silly: why not string the array like so:
echo 'payment_source.value=="'.implode('" || payment_source.value=="',array_values($array)).'"';
echo's: payment_source.value=="[val1]" || payment_source.value=="[val2]" || payment_source.value=="[val3]"
regardless of the number size of the array. Do keep the closing .'"' bit in mind...
Accumulate everything into a string before echoing it, then use rtrim(), then echo it.
<script type="text/javascript">
function hide_card_code() {
var payment_source=document.getElementById('payment_source');
if(<?
echo 'payment_source.value==' ,
implode(' || payment_source.value==', $result_cards);
?>) {
//do stuff...
return true;
}
}

My code (php/js) confuses when I use a variable followed by a number that is bigger than 9

Hello my problem is with my php/javascript code. My variables start from extra1 and ends at extra 12.
The problem is that extra10 , extra11 and extra12 that have two digits confuses the script like there is nothing more than 9.
My code consists of many forms and with this javascript I create a nicer url. Instead of mydomain.com/?extra1=&extra2=abs&extra3=def&extra4= it creates this mydomain.com/?extra2=abs&extra3=def for the php script to get from the url and continue.
Everything works great for variables until extra9.
This is my javascript
<script type="text/javascript">
function formSubmit() {
var extra1 = document.getElementById('extra1');
var extra2 = document.getElementById('extra2');
var extra3 = document.getElementById('extra3');
var extra4 = document.getElementById('extra4');
var extra5 = document.getElementById('extra5');
var extra6 = document.getElementById('extra6');
var extra7 = document.getElementById('extra7');
var extra8 = document.getElementById('extra8');
var extra9 = document.getElementById('extra9');
var extra10 = document.getElementById('extra10');
var extra11 = document.getElementById('extra11');
var extra12 = document.getElementById('extra12');
if (extra1.value == '') {
extra1.parentNode.removeChild(extra1);
}
if (extra2.value == '') {
extra2.parentNode.removeChild(extra2);
}
if (extra3.value == '') {
extra3.parentNode.removeChild(extra3);
}
if (extra4.value == '') {
extra4.parentNode.removeChild(extra4);
}
if (extra5.value == '') {
extra5.parentNode.removeChild(extra5);
}
if (extra6.value == '') {
extra6.parentNode.removeChild(extra6);
}
if (extra7.value == '') {
extra7.parentNode.removeChild(extra7);
}
if (extra8.value == '') {
extra8.parentNode.removeChild(extra8);
}
if (extra9.value == '') {
extra9.parentNode.removeChild(extra9);
}
if (extra10.value == '') {
extra10.parentNode.removeChild(extra10);
}
if (extra11.value == '') {
extra11.parentNode.removeChild(extra11);
}
if (extra12.value == '') {
extra12.parentNode.removeChild(extra12);
}
return true;
}
</script>
and this is the code from the submitted php that gets the data from the url. it's used on wordpress but is a general php programming
for ($i = 1; array_key_exists('extra'. $i, $_GET); $i++) {
$args['meta_query'][] = array(
'key' => 'extra'. $i,
'value' => $_GET['extra'. $i],
'compare' => '=',
);
}
$query = new WP_Query( $args );
As I said everything works fine for variables < 10.
Thank you for your info
In your code, any extraXX which is blank would cause your for loop on the server-side to exit. This means that any extraXX field after the blank one, would not get processed. In order to get around this, you should really be using input arrays (name your fields as extra[] in your html) but if you want to keep all the code you have currently, you can do this:
<?php
foreach ($_GET as $key => $value)
{
if (substr($key, 0, 5) == 'extra')
{
$args['meta_query'][] = array(
'key' => $key,
'value' => $value,
'compare' => '='
);
}
}
This will loop through every $_GET parameter and check to see if it beings with extra, and if it does, add it to your array.
It fails because in alphabetic order, extra10 comes right after extra1. When it finds out that there's no value for extra10, it stops checking for other fields.
Although there are nicer solutions for this problem, using always 2 digitas may work (for instance, extra01, extra02, etc).
To solve your PHP problem, you could do this:
foreach ($_GET as $key=>$value)
{
if (preg_match("#extra(\d+)#", $key))
{
$args["meta_query"][] = array
( "key" => $key
, "value" => $value
, "compare" => "="
)
}
}
$query = new WP_Query( $args );
Your previous code didn't work, because the first non-existing key would cause the for loop to break. For instance, if the 9th field was removed with JavaScript, the loop would have exited at the 8th, leaving all the other ones.
The script above scans all $_GET variables, and only treats those corresponding to the given RegExp pattern (extra followed by any number of digits).
Also, your JavaScript could be a lot shorter and easier to understand like this:
function formSubmit() {
for (var i=1 ; i<13 ; i++)
{
var extra = document.getElementById('extra' + i);
if (extra.value == '')
{
extra.parentNode.removeChild(extra);
}
}
return true;
}
I don't think this is a good idea, it does nothing of any value unless you are expecting your users to read the URL. Anyway, you can just cycle through the form controls and disable any whose value is '', e.g.:
<script type="text/javascript">
function disableEmpties(form) {
var el, elements = form.elements;
var i = elements.length;
var dontDisableTypes = {
submit: 'submit',
reset: 'reset'
};
while (i--) {
el = elements[i];
alert(el.name + ': ' + el.value);
if ((!el.value || el.value == '') && !(el.type in dontDisableTypes)) {
el.disabled = true;
}
}
}
</script>
<form action="#" onsubmit="disableEmpties(this)">
<input name="foo">
<input name="bar">
<input name="glum">
<input type="submit">
</form>

Categories