The following code is the first code in my php page.
$current_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(isset($_REQUEST["lang"])){ //check if different language was selected
$lang = $_REQUEST["lang"];
if($lang == "eng"){
$lang_value = 1;
}else{
$lang_value = 0;
}
setCookie('language',$lang);
setCookie('language_value',$lang_value);
header("Refresh:0; url=".$current_link);
}else{ //if different language was not selected, check if cookie is set with language value
if(isset($_COOKIE["language"])){
$lang = $_COOKIE["language"];
$lang_value = $_COOKIE["language_value"];
}else{ //if cookie with language value is not set, create it now with default language option
setCookie('language','eng');
setCookie('language_value',1);
header("Refresh:0; url=".$current_link);
}
}
The visitor can only choose one of two languages. If a language is chosen, cookies with the chosen language values are created.
If a language is not chosen, the script checks if a cookie with the language value exists, and if so, accesses the cookie values. If a cookie with the language value does not exist, cookies with the default language (English) values are created.
The page is suppose to only refresh when cookies are created and continue the rest of the code if the cookie with the language value exists. However, the page keeps on refreshing even after the cookies were created and are accessible. eg:
echo $_COOKIE["language"]; //will output the selected language value
Not sure if there is something wrong with the logic here, but any help will be appreciated.
Thanks
I managed to solve the mystery.
The problem was in the .htaccess file setup, eg:
RewriteRule diploma-golf course.php?lang=eng&courseid=15 [NC])
Since I only saw the 'diploma-golf' part at the end of the url, I never realised that the "lang" value was passed on every time the page refreshed. So because the script received the "lang" value each time, it created a new cookie each time, resulting in the infinite refreshing. Changed the if statement logic and now everything is working as it should.
Every request to the page will run this part:
if(isset($_REQUEST["lang"])){
That means that the page will be refreshed because of this unconditional part of your code:
header("Refresh:0; url=".$current_link);
What you might want to do is removing the first Header part and only keep the header part as described in your text.
It would look like so:
$current_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(isset($_REQUEST["lang"])){ //check if different language was selected
$lang = $_REQUEST["lang"];
if($lang == "eng"){
$lang_value = 1;
}else{
$lang_value = 0;
}
setCookie('language',$lang);
setCookie('language_value',$lang_value);
#header("Refresh:0; url=".$current_link); ### Removing this line
}else{ //if different language was not selected, check if cookie is set with language value
if(isset($_COOKIE["language"])){
$lang = $_COOKIE["language"];
$lang_value = $_COOKIE["language_value"];
}else{ //if cookie with language value is not set, create it now with default language option
setCookie('language','eng');
setCookie('language_value',1);
header("Refresh:0; url=".$current_link);
}
}
You need to add expire and path for the cookie:
setCookie('language',$lang, time() + (86400 * 30), "/"); // 86400 = 1 day
Related
So I'm currently making a site that includes purchases. Instead of signing up I want to set a cookie then every time a user clicks the buy button, it'll add 1 to the cookie name. Then when the cookie name = $_POST['user'] + 10 I want to echo 'too many right now' or something along those lines. I can't get this to work and have tried multiple times. There is no error in my html or anywhere else in my html. I just can't get this to work. Here is my code:
<?php
$cookie_name = $_POST['user'];
setcookie($cookie_name, time() + (86400 * 30), "/");
if(!isset($_COOKIE[$cookie_name])) {
print 'Cookie with name "' . $cookie_name . '" does not exist...';
} else {
print'Cookie with name "'. $cookie_name .'"value is:'.$_COOKIE[$cookie_name];
}
if(isset($_POST['button'])) {
setcookie($cookie_name, '+1', $cookie_value);
}
if (setcookie($cookie_name == $_POST['user'], +10)) {
echo 'to many right now';
}
?>
I obviously have a html form with the attributes name = 'button' and name = 'user' I just want to know how I can achieve what I said I was trying to do above. Any help is appreciated, thanks.
You are clearly out of your depth, and are hoping that somehow, setcookie will do all the work for you, reading, adjusting, and testing the cookie. As the manual makes clear it does only one thing:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers.
It takes two main parameters: a string which is the name of the cookie to send to the browser, and a string which is the value to send; the other arguments are all optional, and change when and where it will be visible; just ignore them for now. Note that the second argument is not an equation, or an adjustment to be made, it's just a string of text to store.
As ever, the key is to break your problem down; go through each of these steps, and make sure it's working before you go to the next step:
Decide on your cookie's name (the part that won't change, because it's how you'll find it again later).
Test if the cookie has already been set on a previous request.
If it has, put its value into a new variable.
Increment that value by 1
If there is no existing cookie, set the variable to an initial value, like 0 or 1
Send a cookie to the browser with the new value, using setcookie
Test if the value has reached some threshold, and echo a message.
Note that in the above, there is only one call to setcookie; most of your logic is just working with numbers, and doesn't need to know about cookies at all.
So I've scoured w3schools and this fine website for some time but I can't figure this out.
I have a script that creates a cookie in the users session upon loading the browser, and another script that will check the value of said cookie and respond with 2 echo's depending on the value.
Script to create the cookie is:
<?php
$cookie_name = "CTF";
$cookie_value = "ChangeThis";
if(!isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, $cookie_value, time() + 86400, "/", NULL);
}
?>
My IF check for the values is as follows:
<?php
if($_COOKIE[$cookie_value] = "CTF") {
echo "Congratulations. Your token code is 4HeWPzK63Lf5NkGS";
} else {
echo "Your cookie is not set yet.";
}
?>
The code works, and when the cookie is changed to CTF it echo's the correct line. However, when I then delete the cookie and refresh the page, essentially resetting the cookie back to the value of "ChangeThis", the first echo still appears on the page.
Can someone point me in the right direction?
The issue is your if condition. You have used = instead of ==. You are assigning the value instead of comparing. The condition checks if the assignment is successful or not. What you need is the below statement:
if($_COOKIE[$cookie_name] == "CTF")
Also, the cookie value is not "CTF", that's the cookie name, you should compare with the value you are setting it to.
I'm sure this topic had been addressed before, but I can't seem to find an adequate solution to my problem, which I'm sure is not unique.
So I get that you can't set a cookie and expect to use without refreshing the page. So I'm wondering what my options are.
I have a simple set of links that change the language on the page by setting a cookie to that user's language preference. I need to detect that cookie to assign a variable so that I can then change the page output to the designated language.
So, when the button is pressed, it sends a get variable to the URL bar, which then sets the cookie. After I refresh the page, I get what I want.
Basically, I need to pass the GET variable and then refresh the page. How can I do this?
my php code:
// if someone is trying to change the language
if(isset($_GET['lang']))
{
// change the cookie value to that language
$value = $_GET['lang'];
}
// elseif they are not trying to change the language, and a cookie is already set
elseif(isset($_COOKIE['language_pref']))
{
// maintain the value of the language set in the cookie
$value = $_COOKIE['language_pref'];
}
// if get nor cookie is set
else
{
// set default language to english
$value = 'en_US';
}
$name = 'language_pref';
// cookie expires in 2 years
$expireDate = time() + (2 * 365 * 24 * 60 * 60);
$path = '/';
$domain = 'example.com';
$secure = false; //only transmit the cookie if a HTTPS connection is established
$httponly = true; //make cookie available only for the HTTP protocol (and not for JavaScript)
setcookie( $name, $value, $expireDate, $path, $domain, $secure, $httponly);
My HTML:
ZH
EN
Ok so here is what your page looks like:
> Read cookie and get the language
> Read GET variable and SET COOKIE
> Print out stuff in their language
You are simply doing things in the wrong order. If you do things in this order:
> Read GET variable and SET COOKIE
> Read cookie and get the language
> Print out stuff in their language
You'll already have the right language and have no need to refresh the page.
I think all you are missing is the button that links to the url that contains this php.
If your button however you have implemented it has a href containing the url to this page, then when you click on it, you will have refreshed the page and read the contents of the cookie into $value.
try closing the php tags and then adding :
<a href='PAGE_URL_HERE'>button</a>
You could use a php header or JavaScript included in the else component of your code that only gets executed if the statement meets all of your conditions because all you want is to refresh the page after the cookie is set and or read
cleared it up with this php, which allows me to translate the current page according to the get variable and all later pages with the stored cookie
if(isset($value))
{
$language = $value;
}
else
{
$language = $_COOKIE['language_pref'];
}
When a user visits one page I have:
setcookie("firstvisit", time()+3600);
In a functions file which is included in the header of every page I have:
if(isset($_COOKIE['firstvisit'])) {
$run = mysql_query("UPDATE `table` SET `firstvisit` = 1 WHERE `id` = '".$_SESSION['uid']."'");
setcookie("firstvisit", time()-3600);
If I do it like this (and it works) it means the script will run every time the user clicks on that page. Is there any other way to accomplish this?
Your code will only set firstvisit to 1 in the database on the second visit. This is because isset($_COOKIE['firstvisit']) must evaluate to true for the query to run, and cookies are only available in the next request - setcookie() doesn't add to the $_COOKIE array.
// assumes $_SESSION['uid'] is always set
if(!isset($_COOKIE['firstvisit'])) {
setcookie('firstvisit', time()); //set a cookie containing the timestamp of when this user first visited the page
$run = mysql_query("UPDATE `table` SET `firstvisit` = 1 WHERE `id` = '".$_SESSION['uid']."'");
}
else {
//it's not their first visit because the cookie already exists
}
Be aware that this logic won't work on multiple pages - the cookies will overwrite each other and the code will become unreliable.
You can check to see if the cookie is previously set or not before setting it.
if( !isset($_COOKIE['firstvisit']) ){ //if the cookie is not set
//set your cookie
} //skip otherwise
If you don't want to update the value every time. check that value in database whether it's already exist or not?
I want to detect whether the browser is refreshed or not using PHP, and if the browser is refreshed, what particular PHP code should execute.
When the user hits the refresh button, the browser includes an extra header which appears in the $_SERVER array.
Test for the refresh button using the following:
$refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) &&
$_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
If the page was refreshed then you'd expect two requests following each other to be for the same URL (path, filename, query string), and the same form content (if any) (POST data). This could be quite a lot of data, so it may be best to hash it. So ...
<?php
session_start();
//The second parameter on print_r returns the result to a variable rather than displaying it
$RequestSignature = md5($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'].print_r($_POST, true));
if ($_SESSION['LastRequest'] == $RequestSignature)
{
echo 'This is a refresh.';
}
else
{
echo 'This is a new request.';
$_SESSION['LastRequest'] = $RequestSignature;
}
In an AJAX situation you'd have to be careful about which files you put this code into so as not to update the LastRequest signature for scripts which were called asynchronously.
<?php
session_start();
if (!isset($_SESSION["visits"]))
$_SESSION["visits"] = 0;
$_SESSION["visits"] = $_SESSION["visits"] + 1;
if ($_SESSION["visits"] > 1)
{
echo "You hit the refresh button!";
}
else
{
echo "This is my site";
}
// To clear out the visits session var:
// unset($_SESSION["visits"]);
?>
If you mean that you want to distinguish between when a user first comes to the page from when they reload the page check the referrer. In php it is: $_SERVER["HTTP_REFERER"]. See if it is equal the page your script is running on. It may be the case that the client doesn't provide this information, if that happens you could set a cookie or session variable to track what the last requested page was.
To prevent duplicate form processing when a user hits the browser refresh or back button, you need to use a page instance id session variable, and a hidden form input that contains that variable. when the two don't match, then the user has refreshed the page, and you should not reprocess the form. for further details, see:
https://www.spotlesswebdesign.com/blog.php?id=11
If someone refreshes a page, the same request will be sent as the previous one. So you should check whether the current request is the same as the last one. This can be done as follows:
session_start();
$pageRefreshed = false;
if (isset($_SESSION['LAST_REQUEST']) && $_SERVER['REQUEST_URI'] === $_SESSION['LAST_REQUEST']['REQUEST_URI']) {
if (isset($_SERVER['HTTP_REFERER'])) {
// check if the last request’s referrer is the same as the current
$pageRefreshed = $_SERVER['HTTP_REFERER'] === $_SESSION['LAST_REQUEST']['HTTP_REFERER'];
} else {
// check if the last request didn’t have a referrer either
$pageRefreshed = $_SERVER['HTTP_REFERER'] === null;
}
}
// set current request as "last request"
$_SERVER['LAST_REQUEST'] = array(
'REQUEST_URI' => $_SERVER['REQUEST_URI'],
'HTTP_REFERER' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null
);
I haven’t tested it but it should work.