How do I set a PHP session variable from a hyperlink?
My first stab at this so please don't laugh! I've created a session variable to allow users to switch between UK and US content on the same site (UK default).
<?php
session_start();
$_SESSION['territory'] = 'UK';
if (isset($_SESSION['territory'])){
echo 'Session is set to '.$_SESSION['territory'];
}
else{
echo 'Session not set yet';
}
?&开发者_开发问答gt;
All good so far. I now need a couple of links to set this variable when users click either UK or US. All I can Google is setting variables via forms, with nothing helpful about setting via a plain old href. Can anybody steer me in the right direction? Much appreciated.
You can append ?lang=UK to the url, then the $_GET['lang'] variable will be available in your code. For example:
switch($_GET['lang']) {
case 'UK': case 'US':
$_SESSION['territory'] = $_GET['lang'];
break;
default:
$_SESSION['territory'] = 'UK';
}
if you want to set session variable with help of click of link. You will have to use ajax, when you click on a link you can call a javascript function this function can then in turn make a ajax hit to a php file and then this php file can set the session variable.
Firstly, you can do this with just a cookie (no session necessary).
That being said, just create some links to a uri, say: /set_territory.php?cc=UK
and so forth.
set_territory.php can then set the territory via $_GET['cc']
and redirect the user to the appropriate content.
I had the same problem - i wanted to pass a parameter to another page by clicking a hyperlink and get the value to go to the next page (without using GET because the parameter is stored in the URL).
to those who don't understand why you would want to do this the answer is you dont want the user to see sensitive information or you dont want someone editing the GET.
well after scouring the internet it seemed it wasnt possible to make a normal hyperlink using the POST method.
And then i had a eureka moment!!!! why not just use CSS to make the submit button look like a normal hyperlink??? ...and put the value i want to pass in a hidden field.
i tried it and it works. you can see an exaple here http://paulyouthed.com/test/css-button-that-looks-like-hyperlink.php
the basic code for the form is:
<form enctype="multipart/form-data" action="page-to-pass-to.php" method="post">
<input type="hidden" name="post-variable-name" value="value-you-want-pass" />
<input type="submit" name="whatever" value="text-to-display" id="hyperlink-style-button"/>
</form>
the basic css is:
#hyperlink-style-button{
background:none;
border:0;
color:#666;
text-decoration:underline;
}
#hyperlink-style-button:hover{
background:none;
border:0;
color:#666;
text-decoration:none;
cursor:pointer;
cursor:hand;
}
#hide{visibility:hidden;width:0px;}
精彩评论