Injecting cookies using PHP not yielding the same cookie - php

I'm trying to make a PHP script that sets cookies to the browser by reading them from a file first. In the file is the piece of HTTP header "Cookie: x=foo; y=bar; etc". The script does a cleanup of the string so we end up with only the variable name (x) and the value of the variable (foo). The problem is when I set the cookies from the file, using Wireshark I see the exact values of the variables being sent to the broser. When I see what cookies the browser sends to the page, they are different, i.e I set cookie x=foo;, then the browser sends it back to the page as Cookie: x=bar. Do you know what may be causing this? When I use the Greasemonkey script for injecting cookies everything works fine tough.
Here is my code:
<?php
function inject($what)
{
for($i=0;$i<count($what);$i++)
{
$name = $what[$i][0];
echo "injecting cookie named \"$name\" .... <br> ";
setrawcookie($what[$i][0], $what[$i][1]);
}
echo 'all cookies injected properly, ready';
}
$newcook=file("/home/todor/cook.txt");
echo '<pre>';
for ($i=0; $i<count($newcook); $i++)
$newcook[$i] = str_replace('Cookie: ', '', $newcook[$i]);
$newcook = explode('; ', $newcook[0]);
for($i=0;$i<count($newcook);$i++)
$newcook[$i] = explode('=', $newcook[$i]);
for($i=0;$i<count($newcook);$i++)
echo 'cookie variable name "'.$newcook[$i][0].'" with value of "'.$newcook[$i][1].'"<br>';
echo '</pre>';
inject($newcook);
?>
---------------Cookies being set----------------------
Set-Cookie: MoodleSession=h0j51hvrkvu30mdeu3d9321thit8c8pdkle66llr2lipj80chjb0
Set-Cookie: __utma=16796069.1074685784.1352477410.1352477410.1352477410.1
Set-Cookie: __utmc=16796069
Set-Cookie: __utmz=16796069.1352477410.1.1.utmcsr
---------------Cookies being sent to the server -----------
Cookie: MoodleSession=hn92mn8vhl6kvg7f8qogpgm8reeisnoope27o7q3ivrecnr84gb1; __utma=16796069.1720416199.1352484234.1352484234.1352484234.1; __utmb=16796069.1.10.1352484234; __utmc=16796069; __utmz=16796069.1352484234.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)

Related

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.

setcookie(); does not set cookies

I have following problem, I am trying to set cookies without any success. setcookie(); function returns true so it looks like it setting cookie however when I am trying to access it on the same or following page I get error 'Undefined Index....'
<?
session_start();
ob_start();
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',NULL);
//added to see if Cookie is set
echo "<br/>";
var_dump($_COOKIE);
exit();
if($_GET['paypal'] == 1){
header("Location: /paypal-express-checkout/process.php");
}else{
header("Location: /insert_order.php");
}
ob_end_flush();
exit();
?>
next page follows like this
<?php
session_start();
include_once("../includes/inc_config.php");
include_once("../order.php");
include_once("config.php");
include_once("paypal.class.php");
#region POST
if(!isset($_GET['token'])) //Post Data received from product list page.
{
//Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
if(!isset($_COOKIE['order'])){
exit();
}
$paypal_data = '';
$ItemTotalPrice = 0;
$order = unserialize($_COOKIE['order']);
print_r($order);
exit;
You are setting the domain value to NULL. Try leaving the NULL away:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/');
OR set it to your domain:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',".yourdomain.com");
I would var_dump or print_r the $_COOKIE variable before I make a decision that it's not getting passed through. Holding that thought once you setcookie something gets registered into the $_COOKIE variable for sure.
I agree with the statements above since you only can access $_COOKIE on the next refresh but there is another way to do it to make your form or page more interactive.
I would register the cookie and use a php page refresh (display a working... div while thats happening) then come back to the page and try to do what you originally tried doing. Very basic but pretty much straight forward.

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

How to display correct output of Sessions & Cookies in PHP

I have a problem with this program of Sessions & Cookies.
Plz see the following code:-
<?php
session_start(); //session starts
if(! isset($_COOKIE['cnt']))
{
#$_SESSION['nv'] = 1;
}
else
{
#$_SESSION['nv'] += 1;
}
$val = $_SESSION['nv'];
echo $val;
setcookie("cnt", $val, time()+30 );
echo "<h1>No. of visits=".#$_COOKIE['cnt'] ."</h1>";
if (#$_COOKIE['cnt'] == 5)
{
setcookie("cnt", 0, time()-30);
session_destroy();
}
?>
It is not giving the correct output.
When I run the program for the first time, it shows:
No. of visits=
Means nothing..
& when I run the program for the second time, it shows:
No. of visits=1
I want that my output should be displayed as "No. of visits=1" when I run the program for the first time. But it shows this output at 2nd time.
Do help me please..
The cookie set by setcookie is sent along with the HTTP response the server sends to the client and, quoting the documentation:
Once the cookies have been set, they can be accessed on the next page
load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
You should print the session var
echo "<h1>No. of visits=" . $_SESSION['nv'] . "</h1>";

Cookies counter php

I'm trying to do this counter for cookies. The cookies give the right values when I visit the site more than once but for first visit, it always tell me that the cookies(both) are not set. I'm new at PHP so I'm not sure if I missed something. The cookies are set before html tags.
setcookie("user", isset($_COOKIE["user"])? ++$_COOKIE["user"] : 1);
setcookie("date", date("d/m/y h:i:s"));
$count = $_COOKIE["user"];
---------------------------------
<body>
<p><?php
if( $count == 1)
echo "Welcome! You're new here.";
else
echo "Hello, you have visited " .$_COOKIE["user"]. " times.";
echo "<br/>";
echo "Your last visit was ".$_COOKIE["date"];
?></p>
</body>
The setcookie function puts the cookie into the servers http header, which is sent along with the first request. The $_COOKIE array however does not get these values passed internally (from the setcookie function), instead it is generated from the request headers sent by the browser and this only happens after the browser got the cookie (from the first request) and sends it back on the second request.
What you could do is this:
$count = isset($_COOKIE["user"])?$_COOKIE["user"]:1;
I'm not sure but all I see for now is that else is used the false way.
You can write:
if (cond)
do();
else
doelse();
Just single lines work like this.
Use instead:
<?php
if($count == 1)
echo "Welcome! You're new here.";
else {
echo "Hello, you have visited " .$_COOKIE["user"]. " times.";
echo "<br/>";
echo "Your last visit was ".$_COOKIE["date"];
}
?>

Categories