The Cookie set is not detected - php

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.

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?

Counting using session variables and cookies

Probably a dumb question but I just started learning PHP and now I have to do an exercise in which, on the one hand, the session variables have to count how often you have visited the page before closing the browser. And on the other hand, the cookies should count how often you have visited a website in total.
So also if you have closed your web browser, the cookie should continue counting.
This is my problem though.
If I close my web browser and start it again, the cookie starts all over again with counting. How to solve this?
PHP File
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
echo "You have visited this page " . $_SESSION['count'] . " times before you closed your browser";
$count = $_SESSION['count'];
setcookie("count", "$count", time() + 3600);
if (!isset($_COOKIE['count'])) {
$_COOKIE['count'] = ($_COOKIE['count'] + $_SESSION['count']);
} else {
$_COOKIE['count']++;
}
echo "<br> In total you have visited this page " . $_COOKIE['count'] . " times";
?>
You are overwritting the cookie value with the session value.
Instead check if the cookie is already set, and if so, just add to it:
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
$count = $_SESSION['count'];
if (!isset($_COOKIE['count'])) {
setcookie("count", $count, time() + 3600);
$_COOKIE['count'] = $count; //setcookie does not update the superglobal $_COOKIE
} else {
setcookie("count", $count + $_COOKIE['count'], time() + 3600);
$_COOKIE['count'] += $count; //see above
}
//also headers (eg for setting cookies) can only be sent BEFORE the response body, so no echos
echo "You have visited this page " . $_SESSION['count'] . " times before you closed your browser";
echo "<br> In total you have visited this page " . $_COOKIE['count'] . " times";
I think you must set cookie with path
setcookie("count", "$count", time() + 3600, "/");
Most major browsers bundle developer tools that include a cookie inspector. In Firefox it's called Storage Inspector. It can be found in program menus but default short-cut is Shift+F9:
Your cookie should show up there. Also, the Network Monitor (Ctrl+Shift+Q) allows to diagnose whether the cookie is being received and sent back (since you are setting cookies from server-side, the transport mechanism used is HTTP headers).
You should also check PHP manual as often as needed. If your IDE won't generate links from code, there's a little trick you can use: append the function name to http://php.net/, e.g.: http://php.net/setcookie.
Last but not least, you have a condition to run when a given array keys does not exist, yet you use the variable anyway:
if (!isset($_COOKIE['count'])) {
$_COOKIE['count'] = ($_COOKIE['count'] + $_SESSION['count']);
^^^^^^^^^^^^^^^^^
If PHP did not warn you, it's because your PHP set-up is configured to hide it from you. You need to fix it ASAP because coding without the aid of error messages is hard. As quick start, you can set the error_reporting and display_errors directives in your computer's system-wide php.ini file (details here). Errors thumb rule: show in development, log in production.
These tools should suffice to trouble-shoot your issue.

Cookie warning alert doesnt dissapear on first click

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.

Why doesn't my cookie get set

Im trying test the cookie that are set in my browser, earlier cookieid was given inside the url(mydomain.com?cookieid=1234). now im trying to set a cookie by calling the script which sets it. when i load the script known as proceed.php, i want that to go on and set the cookie as i have written. but it does not set the cookie as i intend
proceed.php
<?php
$cookieid = 1234;
include('bin/setcookie.php');
?>
setcookie.php
<?php
include_once dirname(__FILE__).'/../Lodread.php';
$cookieid = isset($_REQUEST["cookieid"]) ? floatval($_REQUEST["cookieid"]) : 0;
$project_id = isset($_REQUEST["projectid"]) ? intval($_REQUEST["projectid"]) : 0;
if (isset($_SERVER['HTTP_REFERER'])){
$urlParts=parse_url($_SERVER['HTTP_REFERER']);
if (isset($urlParts['query'])){
$vars = parse_str($urlParts['query']);
if (isset($vars['cookieid']) && floatval($vars['cookieid']) > 0 ){
$cookieid = floatval($vars['cookieid']);
}
}
}
if ($cookieid) {
if ( ! isset($_COOKIE["cid"])){
$cid = ($project_id?"$project_id:$cookieid":$cookieid);
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/", ".mydomain.com");
header('Location: '.Config_Reader::readProjectConfig('Cookie')->base_url.'/set2.php');
}
}
?>
This is sample, try like this.
How to Get the Contents of a Cookie:
Cookies set for a page can be retrieved from the variable $_COOKIE['cookie_name'] where 'cookie_name' is the name of the cookie you set earlier.
For example, if you wanted to display the value of the "userlogin" cookie, the following code should do the trick.
echo "Welcome back to the site" . $_COOKIE['userlogin'] ;
Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:
/* WARNING: THIS WILL NOT WORK */
setcookie ( "userlogin", "anonymous", time()+60 );
echo "Value of userlogin: " . $_COOKIE['userlogin'] ;
Set Cookie without "mydomain.com".
use this:
setcookie("cid", $cid, time() + 60 * 60 * 24 * 365, "/");
now you check cookie set.
Try it without specifying the domain when using the setcookie function. Also, I would recommend passing $cid directly to your header function since the cookie value can't be retrieved within the same php script right away. Then finally you can see if the cookie is set for future use by using $_COOKIE['cookie_name'] in a separate php script to get the cookie's value.

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';
}
}

Categories