Cookie warning alert doesnt dissapear on first click - php

I created this Cookie alert bar for my site, it works as intented. But you need to click the close link twice to close down the warning for some reason that I cannot figure out.
I use this following function to check if cookie exists or not.
function checkIfCookieExist($cookieName) {
if(isset($_COOKIE[$cookieName])) {
return true;
}
else {
return false;
}
}
if cookie does not exist, and the cookie get parameter exists and equals 1 I create a cookie
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
}
Prints out the cookie bar, links to index with a get parameter for the cookie
function renderCookieBar() {
echo('
<div id="cookieBar">
<p>blabla cookie, cookies on this site yo</p>
I understand, close this box!
</div>
');
}
Calls function to print out cookiebar at given place in my html code
if(!checkIfCookieExist('cookieConfirmation')) {
renderCookieBar();
}
I appreciate any answers or help,
Cheers!

When you set the cookie in the header, the cookie is not directly present; means: the cookie is available up on the next page hit.
Check the manual: http://php.net/set_cookie
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
You can either
1. Set the cookie and immediately reload the page
Set the cookie and force a browser refresah by using header("Refresh:0");.
if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
$cookieName = 'cookieConfirmation';
$cookieValue = 'Cookie confirmation';
$cookieDuration = 86400 * 30 * 3;
setcookie($cookieName, $cookieValue, time() + $cookieDuration);
header("Refresh:0");
}
2. Use Javascript
When setting the cookie with JavaScript it is directly available from the browser. You may also rewrite your script, so the JavaScript sets the cookie and removes the notification bar.
There are many solutions (also here on SO) how to work with cookies in JavaScript easily. If you are using a JavaScript library like jQuery you also have plugins handling the cookies.

Related

Cookie will set, but won't remain set

I know this has been asked many times before, and I've read and tried every suggestion I've found.
I set a cookie in a separate file with the following code:
<?php
session_start();
$q = $_SESSION['qty'];
setcookie ("quantity", $q, time() + (86400 * 30), "/");
$_COOKIE['quantity'] = $qty;
if(isset($_COOKIE['quantity'])) {
print_r("set");
}
else print_r("not set");
?>
It print's "set" every time, indicating to me it has been set. However, in a different php page I test for the cookie with the following code...
if(!isset($_COOKIE["quantity"])) {
include("functions/setQty.php");
}
...and it always takes me to the setQty page, indicating to me that it isn't set (which other issues verify that it's not). What am I missing?

The Cookie set is not detected

Hi guys i set a cookie using my script known as cookieset.php
setcookie("atid", $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
and it is shown in the browser
Name atid
Content 1234
but when i try to retrieve it like this from another script
echo 'value is: ' . $_COOKIE['atid'];
it gives the error saying
undefnied index: atid in.........
can anybody help me over this
setcookie("atid",$atid,time()+315360,"/");
// use
if (isset($_COOKIE['atid'])) {
echo "cookeies set ";
} else {
echo "cookeies not set ";
}
use mozila firebug / cookies to see cookies file
The $_COOKIE array is populated with information sent from the browser. The first time you request the file that calls setcookie - cookieset.php - the server sends the cookie to the browser, but at this time the $_COOKIE array was already populated without the cookie you just set.
The cookie will be available in subsequent requests until it expires.
To see the cookie in PHP, just do like this.
if (isset($_COOKIE['atid'])) {
echo 'Cookie found with value ' . $_COOKIE['atid'];
} else {
setcookie('atid', $atid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
echo 'Cookie was set. Please refresh to see it working';
}
The problem (from the error), seems to be that $_COOKIE['atid'] (depending on what line the error is at) is undefined - that means it has not been set, and seeing that you actually set the cookie, I am saying that its the atid that is undefined. Make sure you are getting it, check with isset()
Try this :
if (isset($_COOKIE['atid'])) {
echo $_COOKIE['atid'];
} else {
echo "No cookie Set";
}
And one more point :
it won't be available until the next page load or by doing the page request again.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

Cookie Not Available Sitewide

I'm having two issues with setting and retrieving cookies.
Cookie gets loaded but can't be called until page is refreshed. Meaning that the cookie shows up in developer tools but not when trying to use its value on the page. The value does seem available to use on page after refreshing.
Cookie is not available across entire domain and subdirectories. For example, if the user enters at http://example.com/sub/ the goes to http://example.com/, the cookie gets destroyed.
Here's my code:
$ad_source = $_GET['source'];
$date_of_expiry = time() + (86400 * 7);
setcookie('ad_source',$ad_source,$date_of_expiry,'/');
if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
echo '... do something';
} elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
echo '... do something else';
}
I'm trying to to show different information throughout entire site by determining what adwords campaign the user clicked in on.
I don't usually use cookies and prefer to set a session, but in this case I want be able to track the source for a longer amount of time.
Everything is working as expected now. A little more insightful information into cookies at this post helped a lot.
PHP cookie set in second refresh page
Redirect user to page after cookie is set. Second request from browser sends cookie, server returns info relative to its value.
Check to see if $ad_source is set before creating cookie.
The updated code:
$ad_source = $_GET['source'];
$date_of_expiry = time() + (86400 * 7);
if ( $ad_source ) {
setcookie('ad_source',$ad_source,$date_of_expiry,'/','example.com');
if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
header( 'Location: http://example.com/' );
echo '... do something';
} elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
header( 'Location: http://example.com/' );
echo '... do something else';
}
}

Can't make users login for long period of time

I have this platform which you can login and do your tests (this is a test link): www.mf.pt.la
I can't understand why this isn't working... first I tried this on top of my config.php file:
ini_set('session.cookie_lifetime', 864000);
ini_set('session.gc_maxlifetime', 864000);
Than I tried this with a cookie:
$year = time() + 31536000;
if($_POST['remember']=="1")
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
elseif($_POST['remember']=="")
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}
None seem to work because after 30mins/1h user is logged out! :(
This is very frustrating because inside this website users are usually getting in a out more than once per day, and having always to login is making me lose users actually! :(
EDIT 1:
Ok, so let's see where we are at this point.
After a lot of tests, I have noticed the problem was that I was trying to save an array directly into the cookie and it doesn't work like that. I have searched a lot and created a very simple cookie with name "test" and content "text" and it worked, so if what was working I did created a cookie!
Then I searched for a way to put it working all together on the same cookie instead of save one cookie for each information I needed.
So this is the conclusion. To create the cookie, this is what I've made:
$cookie_name = "remember_me";
$userinfo = $_SESSION[LOGIN_USER]['user_id']."_".$_SESSION[LOGIN_USER]['user_type']."_".$_SESSION[LOGIN_USER]['name']."_".$_SESSION[LOGIN_USER]['email'];
if($_POST['remember']=="1"){
setcookie($cookie_name, $userinfo, time() + 31536000, '/');
}else{
setcookie($cookie_name, $userinfo, time() + 864000, '/');
}
And to call the cookie this is what I have made:
if(isset($_COOKIE["remember_me"])) {
$usercookie = explode("_",$_COOKIE["remember_me"]);
$_SESSION[LOGIN_USER]['user_id'] = $usercookie[0];
$_SESSION[LOGIN_USER]['user_type'] = $usercookie[1];
$_SESSION[LOGIN_USER]['name'] = $usercookie[2];
$_SESSION[LOGIN_USER]['email'] = $usercookie[3];
}
So far, it seems to work, but... let's see if in some more hours the login is done automatically after I enter the website again.
EDIT 2:
Just noticed that spaces are saved into cookie as + and # as %40
EDIT 3:
FINALLY! I did it and here's what I did in order to help future users:
First, let's start by creating the cookie. I inserted a new colum in my users table to save a token, and assigned that token as an encription in MD5 to a variable, like this:
$tokenuser = md5(uniqid(rand(), true));
Once the table was updated, we must create the cookie, and here it is:
$cookie_name = "mfrm";
if($_POST['remember']=="1"){
setcookie($cookie_name, $tokenuser, time() + 31536000, '/');
}else{
setcookie($cookie_name, $tokenuser, time() + 864000, '/');
}
For those who didn't understood that "if" condition, that's simply to check if the user have selected the "checkbox" in order to be remembered "forever" (one year in this case).
So far so good, the next part was the one that was "try and error" until I finally did it! You should put this code BEFORE your headers, because otherwise it might not work and will probably give you an error:
if(isset($_COOKIE["mfrm"])) {
$usercookie = $_COOKIE["mfrm"];
}
So, this way your variable $usercookie now has the content of your cookie (the unique token we created).
"Later" on your code, you simply do a call to your database, check for which user that token is valid and then just asign user_id and all other things you want in order for user to have his login. :)
I hope whoever sees this can solve the problem, I did a LOT of Google search before I finally get this working.
My suggestion is, do a lot of "print" and "echo" in PHP so you can see where is your problem, if needed stop your code by inserting sleep(2); (where 2 means two seconds)
Good luck! :)
This won't suffice, cookies are saved in user's browser, so every time she connects, you check her cookies and and set set up her session accordingly.
Hope this helps
=== EDIT ===
This may help you: http://www.pontikis.net/blog/create-cookies-php-javascript
Let's say that the user ID is '12345', and he is logging in
You set the cookie with:
setcookie('user_id', '12345', time() + (86400 * 30), '/');
Then, then if the user logs in tomorrow, and his session has expired, you check if his user_id exists in DB from the cookies:
if(isset($_COOKIE['user_id'])) {
// check the user_id in DB and create session if exists
}else{
// User has no cookies, then he has to login
}
Hope this makes sense.
This is a very simple example, so of course, do not just put a user_id in your cookies, but a more rigorous form of authentication, like the last session id and a token you'd have generated.
=== EDIT2 ===
Is 'remember' the name of a checkbox? Because in which case, if it is not checked, $_POST['remember'] is not set. So instead of checking the value of $_POST['remember'], you should check if it is set or not
Assuming that 'remember' is the name of a checkbox:
$year = time() + 31536000;
if(isset($_POST['remember']))
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
else
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}

Include different content based on variables

I'm using this method to display different content based on the variable that was passed down from my previous page.
<?php
if (isset($_GET['click'])) {
if($_GET['click'] == 'person'){
file_put_contents('person.txt', ((int) file_get_contents('person.txt')) + 1);
include 'resultperson.php';
} elseif ($_GET['click'] == 'text'){
file_put_contents('text.txt', ((int) file_get_contents('text.txt')) + 1);
include 'resulttext.php';
} elseif ($_GET['click'] == 'online'){
file_put_contents('online.txt', ((int) file_get_contents('online.txt')) + 1);
include 'resultonline.php';
}
} else {
include 'resulttext.php';
}
?>
Problem is, when I hit refresh, the file_put_contents() function will be executed again. It's just a way that I use to track how many times users have clicked that button.
How do I prevent the increment of the integer being injected upon refreshing the page?
Or if there's a simpler method doing all this?
Using a session is probably your best bet, unless you don't mind that when the user closes the browser and visits the page again it will be triggered.
// This will be set to true if the user has the session variable set
$clicked = isset($_SESSION['clicked']);
// Check if get variable 'click' is set, and that $clicked is false.
// If 'click is set and $clicked if false, the variable $click is set to the
// value of $_GET['click'] (for example 'person'). Other wise it will be set to false.
$click = (isset($_GET['click']) && !$clicked) ? $_GET['click'] : false;
// Set the session variable 'clicked' if it isn't set so that the next time
// the user visits, we'll know
if (!$clicked) {
$_SESSION['clicked'] = 1;
}
if($click == 'person'){
file_put_contents('person.txt', ((int) file_get_contents('person.txt')) + 1);
include 'resultperson.php';
} elseif ($click == 'text'){
file_put_contents('text.txt', ((int) file_get_contents('text.txt')) + 1);
include 'resulttext.php';
} elseif ($click == 'online'){
file_put_contents('online.txt', ((int) file_get_contents('online.txt')) + 1);
include 'resultonline.php';
} else {
include 'resulttext.php';
}
If you want to track where the user has come from, you can use the referer field of the http header.
If that's not an option, you could have your click link to a php page that registers the click, and then do a header("Location: x.php"); to the page that displays the content.
With your actual code, you can't prevent the increment of the integer on a page refresh.
The question is: does it matter? How important and accurate you want your tracker to be?
There is a way to attach the increment to the button click, which is to use AJAX. You can attach a handler to the button click event, which makes the appropriate AJAX call to the PHP script.
This is not simpler, but it is simple.
Both this solution and your actual one can't prevent a malicious user to make HTTP requests to call your PHP script, incrementing your counter at will...
This should work, and is simpler, and more easily extendable:
<?php
if (isset($_GET['click']) && isset($_SERVER["HTTP_REFERER"])) {
$click = $_GET['click'];
if (in_array($click, array('person', 'text', 'online')) {
file_put_contents($click . '.txt', ((int) file_get_contents($click . '.txt')) + 1);
include 'result' . $click . '.php';
}
} else {
include 'resulttext.php';
}
?>
You could use an ajax-call to trigger that operation. This way the url gets called "behind the scenes" without reloading the content. I recommend this option; using JQuery ajax it can be as simple as writing a onClick function like function clicked(){$.ajax("yourClickCounter.php");} and then adding <button ... onClick="clicked()">...</button> to the html. Of course, you would then have to have the clickCounting done in a separate PHP-file, but it has the advantage of not reloading all the content every time the button is clicked.
You could use a session variable like $_SESSION['has_clicked']. This requires that you start a session first, with session_start()
To diferentiate when a user visits the page from your previous page, rather than hitting refresh, look at the $_SERVER["HTTP_REFERER"] variable. That variable will contain the url of the previous page from when the user came, but in the case of a refresh, that variable will not exist as the user hasn't come from any page (he didn't click a link to get to your page) instead was the browser that sent the request.
If your previous page is called 'mypage.php' for this matter, then replace your following line:
if (isset($_GET['click'])) {
for this one:
if (isset($_GET['click']) && isset($_SERVER["HTTP_REFERER"]) && strpos($_SERVER["HTTP_REFERER"],'mypage.php')) {
that should do what you want.
Update:
Above solution will not work as when hitting Refresh on browser the page will maintain the same Referer value.

Categories