Redirect certain urls based on location - javascript

I have a number of links to Amazon UK on my (Joomla 3.4) website - these are links to buy books. They are basically 'Buy Now' buttons that take the user to the relevant Amazon UK item page (e.g www.amazon.co.uk/myBook) - html code below
<a class="btn btn-primary" href="http://www.amazon.co.uk/myBook...">Buy</a>
What I would like to do is re-direct US visitors to www.amazon.com
<a class="btn btn-primary" href="http://www.amazon.com/myBook...">Buy</a>
I know I could just add another button ('Buy US') but I only want one button per page.
I though I could perhaps either modify the .htaccess file, or add some javascript code so that vititors from the us will be taken to .com and not .co.uk?
I was looking at the geoPlugin and IP2Location - can either or these be used to achieve this?
Perhaps I could modify the IP2Location code (below) somehow?
<?php
require_once 'IP2Location.php';
$loc = new IP2Location('databases/IP-COUNTRY.BIN', IP2Location::FILE_IO);
$record = $loc->lookup($_SERVER['REMOTE_ADDR'], IP2Location::ALL);
if($record == 'US') {
header('HTTP/1.1 301 Moved Permanently');
header('Location: http://amazon.com');
exit;
}
?>
Not sure how I can user server side includes to achievce this?
Any help or direction is appreciated, I'm keen to learn by myself.

You can edit /index.php in Joomla to as below:
$output = ob_get_clean();
require_once JPATH_LIBRARIES . '/IP2Location.php';
$db = new \IP2Location\Database('./databases/IP-COUNTRY-SAMPLE.BIN');
$records = $db->lookup($_SERVER['REMOTE_ADDR']);
if($records['countryCode'] == 'US'){
echo str_replace('www.amazon.co.uk', 'www.amazon.com', $output);
}
else{
echo $output;
}

Related

Change navigation menu when user is logged in HTML

I have a site in HTML, where I implemented login and register system using PHP.
When there is no user logged in, the navigation item "Contul meu" from every page need to send me to "gotosigning.html" page.
However, when the user is logged in I want that the menu item "Contul meu" from every page to send me to "account.html" page.
Some menu items for example, in the index.html page:
<li class="active">Acasă</li>
<li>login</li>
<li>sign in</li>
<li>Contul meu</li>
the gotosigning.html page redirects to a page where you can select if you want to sign in or login, and based on the selection here you go to login.html or signin.html.
This is the basic example,when the user is not logged in, but when it is, the last item should become <li>Contul meu</li> in all the pages.
login.php, which is implemented in the login.html and signup.html pages
<?php
$link = new mysqli("localhost", "root", "", "graphicdesign");
if($link->connect_error){
die("ERROR: Nu s-a putut realiza conexiunea la baza de date " .$link->connect_error);
}
session_start();
$email =$_POST['email'];
$password=$_POST['pass'];
$result = $link->query("SELECT email_cl, parola_cl FROM clienti WHERE email_cl= '".$email."' AND parola_cl= '".$password."'");
if($result->num_rows == 0 ) {
echo "Datele nu corespund!";
}
else {
$_SESSION['logged in']=true;
$_SESSION['email']=$email;
echo "Login cu succes!";
echo "<script>setTimeout(\"location.href = '../account.html';\",1500);</script>";
}
?>
How can I make the server know all the time which the user is logged in?
And how can I tell the HTML pages when to update their navigation based on that state of logged in or not?
The only thing I thought about was to duplicate all the pages ( but they are too many ) and then implement some code to test if the user is logged in to the server can choose the choice with the right menu... but doesn't seem okay at all...
Thank you!
First, you need to rename all your pages from .html to .php. There is absolutely no difference between the two extension except for this: if the page ends in .php, then the PHP processor knows to interpret any PHP code found between <?php and ?> tags. If the page ends in .html then the PHP will not be processed. HTML will continue to work exactly the same. Try it now - create a test page with some HTML in it and name it with the .php extension. You will see it works exactly like one ending in .html
In order to change the navigation items after the user has logged in, you can refer to the $_SESSION variables that you set when they logged in. Note: do not use spaces in session variable names - underscore chars (eg logged_in) are fine, though.
Example:
<?php
if ($_SESSION['logged_in'] == true){
$out = '<li>Contul meu</li>';
}else{
$out = '<li>Contul meu</li>';
}
echo $out;
?>
And, most important - make sure that you put session_start(); at the top of every PHP file.
As a side note, I personally like to have a <?php ?> section at the top of my PHP files that contains as much of my PHP code as possible. For example, I would place the above code right up at the top of the file -- before any HTML -- before <!DOCTYPE html>. Then, I have all my HTML code and -- where it belongs -- I echo out the PHP variable, like this:
<li class="active">Acasă</li>
<li>login</li>
<?php echo $out ?>
<li>sign in</li>
(I intentionally placed your Contul meu menu item for DEMO purposes, so that you can see stuff above it and also below it. In your example, it was the last menu item which would not be as clear for demo purposes.)
you can display your menu based on condition. Put a check using session on the top of every login/logout and signin page like that:-
Note: you make your start session on top of every file.
<?php
session_start();
if(isset($_SESSION['email']) && !empty($_SESSION['email'])){
?>
Logout
<?php
}else{
?>
<li class="active">Acasă</li>
<li>login</li>
<li>sign in</li>
<li>Contul meu</li>
<?php } ?>

Need help creating the php and/or javascript using a hyperlink to change the language on a webpage

I have previously used a dropdown selection box with options using a post method in order to change the language in a webpage that is saved on a separate file. I am now trying to create something similar but need help. Now I am trying to make the webpage for only 2 languages and when viewing the webpage on one language the option to switch to the other will appear. Essentially giving the viewer the option to change the session language to either English or Spanish only with showing the opposite language as a hyperlink on all pages. My language file is essentially as follows:
<?php
$lang = array(
'EN' => array(
'ABOUT' => 'About',
'HOME' => 'Home'
),
'SP' => array(
'ABOUT' => 'Acerca',
'HOME' => 'Casa'
)
)
?>
This PHP code that I have shown here is more extensive but this is how I set things up writing these lines of code on another file to be able to change the language. On my main page I have a short section of code before the html document is declared and that is as follows:
<?php
require("lang.php");
session_start();
$_SESSION['LANG'] = "EN";
if(#$_POST['lang-chooser']){
$_SESSION['LANG'] = $_POST['lang-chooser'];
}
?>
I am trying to make the portion of the page where I have the hyperlink to be located in the header or body of the document. The code I have currently for the option to choose a language is as follows:
<form method="post" action="" id="lang-form">
<select id="lang-chooser" class="lang-chooser" name="lang-chooser" onchange="window.lang(this);">
<option value="EN"<?php if($_SESSION['LANG'] == "EN") {?> selected="selected"<?php }?>>English</option>
<option value="SP"<?php if($_SESSION['LANG'] == "SP") {?> selected="selected"<?php }?>>Spanish</option>
</select>
</form>
Underneath my footer but still in the body portion I also have a little amount of script as follows:
<script type="text/javascript">
function lang(element){
var lang_name = element.value;
var e_form = document.getElementById("lang-form");
e_form.submit();
console.log(element);
}
window.lang = lang;
</script>
With all of these portions of code I was successfully able to change the language using the dropdown selection box while staying on the current page. The code I would use to have changeable text would be as follows:
<?php echo ($lang[$_SESSION['LANG']]['ABOUT']); ?>
Now I wish to have the option to change the session language on any page again but without the dropdown selection box. I wish to have it so that when the page is in English which it automatically should be when accessing the site there will be a hyperlink named Espanol which allows the viewer to change to Spanish and once the page is in Spanish the hyperlink will change to saying English which allows the viewer to change to English. From looking online I am lead to believe that I will still need the intro PHP code and javascript but will no longer need the "form" or "method" portion to change the session language. I believe all that I need now in replacement of the "form" and "posting-method" is as follows:
<?php echo($lang[$_SESSION['LANG']]['SPANISH']); ?>
I believe that my code is still lacking and this is why I still cant get it to work. Essentially I will need the hyperlink to change text according to the session and to also be used to change the session language from either Spanish or English. I am a little stumped here and would very much appreciate any kind of help. Thanks for taking the time to read this question.
You could replace your form with php if, else and get functions.
By using $_GET at the head of the page you can check if lang is set in the URL and set a session based on the result:
Edit
This section will replace everything after session_start(); in the second piece of php code you placed in the question.
<?php
if(!isset($_SESSION['LANG'])){
$_SESSION['LANG']='EN';
header('location: '.$_SERVER["REQUEST_URI"]);
}
if(isset($_GET['lang'])){
if($_GET['lang']=='sp'){
$_SESSION['LANG']='SP';
}else{
$_SESSION['LANG']='EN';
}
}
After you can check if the session is set then call out a href link to whichever language you want to change to.
This section will replace the html form
<?php
if(isset($_SESSION['LANG'])){
if($_SESSION['LANG']=='EN'){
echo 'Espanol';
}else{
echo 'English';
}
}else{
echo 'Espanol';
}
You don't need java to achieve this.
EDIT
If you want the URL not to show the ?lang= you can include another session and a header in the first section such as:
<?php
if(isset($_GET['lang'])){
if($_GET['lang']=='sp'){
$_SESSION['LANG']='SP';
header('location: '.$_SESSION['URI']);
}else{
$_SESSION['LANG']='EN';
header('location: '.$_SESSION['URI']);
}
}else{
$_SESSION['URI']=$_SERVER["REQUEST_URI"];
}
This will instantly redirect the user back to the page they were on, they shouldn't notice the refresh.
<?php
$allowed_langs = array('EN' => 'English', 'SP' => 'Espanol');
$site_lang = isset($_SESSION['LANG'])?$_SESSION['LANG']:'EN';
//Here you can set language according to link
if(isset($_GET['lang'] && in_array($_GET['lang'], $allowed_langs)){
$_SESSION['LANG'] = $_GET['lang'];
$site_lang = $_GET['lang'];
//Then you can refresh the page if you want to load new file or start
// including your language file after this language set.
}
//include your lang file
include_once( 'langs/' . $site_lang . '/text.php' );
?>
<ul>
<?php
foreach($allowed_langs as $langshort => $langlong){
$new_query_string = build_query_string($param, 'lang', $langshort);
$new_link = strtok($_SERVER["REQUEST_URI"],'?') . "?" . $new_query_string;
$class = ($_SESSION['LANG']==$langshort)?'selected':'';
?>
<li class="<?= $class ?>"><?= $langlong ?></li>
<?php } ?>
</ul>

WordPress is_user_logged_in failing with HTML Scripting

Could someone please review why this below added code won't execute correctly? I've escaped the PHP scripting to display the HTML content in WordPress, but I can't get this thing to work!
The results are that, whether the user is logged in or not, the HTML content displays for everything. Strangely, though, I can't get the else { ... } part to render in HTML. I'm not too good with PHP, so please mind if I done something incorrectly.
I've tried debugging via NetBeans, but the IDE failed to detect anything on a fail-safe conditioning.
<?php
if ( is_user_logged_in() ) {
?>
<h2>Welcome to the Portal!</h2>
<p>Here you can manage all information with an authorised account. You can click on the button below to create a new entry.</p>
<button type="button" href="#" onClick="document.location = 'http://www.example.com'">Add Entry</button>
<?php
} else {
echo "<h1>Unauthorised!</h1>";
echo "<javascript>document.location = \'http://example.com\'";
exit;
};
?>
Alright, so I got the coding going. It turned out that, by default, WordPress didn't allow PHP execution in my pages. I installed a plugin named "insert PHP", modified the code to mix html and php and it worked!
[insert_php]
if (is_user_logged_in()){
echo "<h2>Welcome to the Portal!</h2>";
echo "<p>Here you can manage all entries with an authorised account. You can click on the button below to create an entry.</p>";
echo '<button type="button" onClick="document.location = \'http://somesite.com\'">Add Listing</button>';
} else {
echo '<h2>Unauthorized 401</h2>';
echo '<script>document.location = \'http://domain.tld'</script>';
};
[/insert_php]

How set id from database to php session on link click

but lets talk from the begin. I am creating website similar like wordpres blog index page (can't show picture bescause dont have enough reputation). And then I click read more link in the intro article I want save that article id from the database to php sesions. Here is the code.
while($row = mysqli_fetch_array($result))
{
echo '<div class="img">
<img src="img/smiley.gif" alt="Smiley face" width="250" height="250">
</div>';
echo "<h2>".$row['Name'] . "</h2> " ;
$string = strip_tags($row['Content']);
if (strlen($string) > 500) {
$stringCut = substr($string, 0, 500);
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).'... Read more';
}
//echo $string;
if(isset($_GET['link']) /*you can validate the link here*/){
$_SESSION['link']= true;
}
echo $string;
echo "<br>";
echo '<div class="content dashboard clearfix"></div>';
echo '<hr>';
}
mysqli_close($con);
?>
So I have 3 intro articles in index.php file and I whant read one, so I press READ MORE (then I should write article id to session) and go to other page, were I think I should get articles id from session. I am tryyng do it with
if(isset($_GET['link']) ){ /*you can validate the link here*/
$_SESSION['link']= true;
}
But it always write number 5 the last ID from database, so I think I should use maybe AJAX, javascript?? Maybe some one can give me the example?
Thank you.
You could set a SESSION variable through ajax but... that'd get pretty insane, making things overly complicated and not very SEO friendly
There's a better method: Make your "read more" actual links to your content. So you've got a "read more" link to http://example.com/page.php?id=5, then inside "page.php" you simply do:
$Id = intval($_GET['id']);
You can make this more pretty after reading how to create friendly URL in php? so they look like http://example.com/page/5.
From your code, you automatically go to the desired page when clicking on the link. Therefore, you only need to create the page post.php and retrieve a single row from the database, in a similar fashion as I indicated above but with the proper name:
$Id = intval($_GET['link']);

href call in javascript

I have a problem with using , during
click of the link, I need to update a field in the database and redirect to another page after.
I have this code:
<a href="#" onclick="<?php
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."'
WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
$logger->debug('OK');
}
else
{
$logger->debug( 'NOt OK');
}
?>"> </a>
After the php end tag '?>' can I add my path to be directed to? like:
<a href="#" onclick="<?php
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."'
WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
$logger->debug('OK');
}
else
{
$logger->debug( 'NOt OK');
}
?> ../index.php"></a>
Is that even possible?
What is the right thing to do it?
Thanks a lot!
this is not the right way.
There can be multiple ways you could take to do this. But I'd suggest you to place the DB update code in the target page (that I assume you mentioned as index.php). If you only want to trigger the DB update code on clicking of the link, use a page in middle to redirect the flow.
So, your page flow will be:
Current Page (Link Clicked, simple href to middleman.php) ==> middleman.php (just run the DB update code here and use header Location syntax to index.php) ==> index.php
codes:
page in which you have the link
source.php
<.... html contents ....>
<a href='middleman.php'>Visit the page</a>
<.... more html contents ....>
middleman.php
<?php  
$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."' WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
$logger->error(mysql_error());
}
if ($sql)
{
 $logger->debug('OK');
}
else
{
 $logger->debug( 'NOt OK');
}
header("Location: index.php"); //redirects to index.php
?>
index.php
do whatever you want
When a page is rendered, php code will run once. Whenever you see a webpage, it's only html, always, with no live access to the php code. So, you cannot execute php blocks directly from for example a javascript event. In your case the sql query would execute once, when you load the page.
kishu27 just posted one of the proper ways to do it, and the best option for you in this case. If you only wanted to update the database, without being redirected to another page, an ajax call to a php page with the database code would be a good alternative.
Using location.pathname

Categories

Resources