Not displaying cookie count correctly - php

I have one file basket.php that displays the count perfectly, but in the other php file product.php it always displays 0 the codings are below:
basket.php
<?php
//include(dirname(__FILE__)."/../config.php");
if (isset($_COOKIE["products"])) {
//Count of all products in basket
$BasketCount = count($_COOKIE['products']);
//Loop through and get each cookie
foreach ($_COOKIE['products'] as $name) {
$name = htmlspecialchars($name);
echo "$name <a href='remove.php?remove=$name'>Click here to remove from basket</a> <br />\n";
}
echo "Basket Count: $BasketCount";
}else{
echo "Basket is empty";
}
?>
product.php
(just the line that gets the basket count)
$basketcount = count($_COOKIE['products']);
Here is how i set the cookies
addtobasket.php
<?php
include(dirname(__FILE__)."/../config.php");
$product = $_GET['p'];
setcookie("products[$product]", $product);
echo "$product added to basket";
//Show current basket products
?>

May be issue with path - http://www.php.net/manual/en/function.setcookie.php, $path parameter. Or domain.

Not the actual answer, but nevertheless related:
Assuming you're making a commercial website with a basket/shopping cart system, I would advice this:
DO NOT RELY ON COOKIES, never. It's stored on client side and can be modified easily. Moreover some browser simply refuses them, and thus your basket won't work.
Use $_SESSION[] instead, they only store the identifier client side. Safer, both against hacking code flaws and anything.

may be you are running product.php before cookie is set..
other than that code is fine to me.
or you can check cookie is set or not by this code..
if(isset($_COOKIE['products'][$product])){
echo "cookie is set..";
}
so that you will have exact idea..

Related

How to pass PHP $_SESSION value to new page

Im trying to figure out how to use a php $_SESSION value. The situation is:
Main HTML site has an <iframe> that loads products.php
Within products.php a form submits and saves the two values below:
$_SESSION["subtotal"] = $_POST['SUBT'];
$_SESSION["tax"] = $_POST['TAX'];
These work well I can echo them no problem (within that page)
This page replaces products.php with confirmation.php
Once in the confirmation.php I am not able to grab the session values. I have tried the following:
<?php
session_start();
$_SESSION["subtotal"] = $_POST['SUBT'];
$_SESSION["tax"] = $_POST['TAX'];
echo $_SESSION["subtotal"];
echo $_SESSION["tax"];
echo $subtotal;
echo $tax;
?>
AND
$_SESSION["subtotal"] = $subtotal;
$_SESSION["tax"] = $tax;
echo $_SESSION["subtotal"];
echo $_SESSION["tax"];
echo $subtotal;
echo $tax;
?>
AND
$subtotal = $new_subtotal;
$tax = $new_tax;
echo $new_tax;
echo $new_subtotal;
?>
All have failed to see $_SESSION - Is the value getting lost with the <iframe> change?
I have used the following code on the products.php page to confirm the session were susecssfully created - They are:
echo $_SESSION["subtotal"]." stored in session <br />";
echo $_SESSION["tax"]." stored in session <br />";
NOTES:
Both confirmation & products.php are on the same server.
print_r($_SESSION); Returns BLANK array.
session_start() is at the very top of both pages
Use something like this:
products.php
<?php
session_start();
$_SESSION['myValue']=$_GET['YourFormElement'];
//or
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
I did that once by adding $_SESSION to url inside iframe and in file that is used in iframe I used that $_SESSION by $_GET.
I am not sure 100% but it should work as:
$session = $_SESSION['session'];
<iframe src="somePage.php?s=<?php echo $session; ?>"></iframe>
somePage.php
if(isset($_GET['s'])){
$session = $_GET['s'];
}

Data wasn't able to retrieve from the previous page (PHP and MYSQL)

I researched here in stackoverflow trying to find whether someone is also encountering the same problem. I know it's kind of easy and even I really don't know what's the error because there's no problem with my query.
On the previous page, here's my code to retrieve the ID Number so I'll be able to select the data with that ID number:
<?php echo $row['place_name'];?>
I tried first to print the value of the place id and it works fine.
But when it was being called to the Package page, the data I want to show weren't displayed.
I look at the URL and it shows this after the package.php
place_id=
I don't know why it is blank, please check my code if there's missing or just wrong.
In my package page, here's the PHP code:
<?php
include("common/connect.php");
$place_id = $_GET['place_id'];
$result = mysql_query("SELECT * FROM package_items WHERE place_id = '$place_id'");
$row1 = mysql_fetch_array(mysql_query("SELECT place_name FROM packages WHERE place_id = '$place_id'"));
if($result === FALSE) {
die(mysql_error()); // for better error handling
}
?>
In HTML Code:
<h1><?php echo $row1['place_name'];?></h1>
<?php while($row=mysql_fetch_array($result)) {?>
<?php echo $row['item_title'];?>
<br>
Back
<?php } ?>
Please check my codes. Thanks.
You are not printing it.
Change
<?php $row['place_id'];?> // It will output nothing as no echo or print.
To
<?php echo $row['place_id'];?>
Rest of the code looks fine.
Three suggestions:
1)
$place_id = $_GET['place_id'];
Change to
$place_id = ! empty($_GET['place_id']) ? $_GET['place_id'] : ''; // To avoid any warning.
2) Don't feed variable from $_GET or $_POST to any SQL.
3) Don't use mysql_ functions as they are deprecated and will be remove in future versions of PHP.

PHP Sessions Remove Cart Iitems

I have been searching around for help but can't find anything that will fix my problem
I have manipulated a cart code to serve a different a purpose Im bulging a role-play assistance site www.rptoolkit.com/encounter where you add NPC's to the encounter (Cart) and you can then remove them when needed, the site is online if you want to check
the issue is script works perfectly fine in XXMP hosting on my local host but online live, if i add 4 people to the list and try to delete 1 they all clear and the first line gets duplicated (feel free to test)
below is my script code i have used for the delete item button
<h1>Curent Encounter</h1>
<div class="encounter-table">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["encounter"]))
{
$cart_items = 0;
foreach ($_SESSION["encounter"] as $cart_itm)
{
$id = $cart_itm["code"];
$results = $mysqli->query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$obj = $results->fetch_object();
echo '<td><span>
<a href="include/encounter_remove.php?removep='.$cart_itm["code"].'&return_url='.$current_url.'"><img src="images/icon_delete.gif" alt="Delete"><
/a></span></td>';
and below is the code I have to remove items from the encounter (cart)
<?php
session_start();
include_once("config.php");
//remove item from encounter
if(isset($_GET["removep"]) && isset($_GET["return_url"]) && isset($_SESSION["encounter"]))
{
$id = $_GET["removep"]; //get the product code to remove
$return_url = base64_decode($_GET["return_url"]); //get return url
foreach ($_SESSION["encounter"] as $cart_itm) //loop through session array var
{
if($cart_itm["code"]!=$id){ //item does,t exist in the list
$product[ ] = array('code'=>$cart_itm["code"]);
}
//create a new product list for cart
$_SESSION["encounter"] = $product;
}
//redirect back to original page
header('Location:'.$return_url);
}
?>
I would love any help or advise i can I've to fix it, I don't know if its coming downy to the different PHP versions from my XXMP to the server possibly?
Thanks again,
Trev
Session variable size can be limited by the browser. Depending on how much data is stored in `$_SESSION['encounter'], you may be reaching the limit. Consider only storing a id numbers or something similar instead of more complex objects and/or arrays.

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.

PHP counter file and page forwarding

So i'm writing this code so that you either get forwarded to a certain page if you're the first one to hit the link, or you are sent back to the original page after being displayed a message if you're not what beginner mistake am i making?
<?php
$count = file_get_contents('counter.txt');
$count = trim($count);
if ($count="0")
{
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);
header("Location: newpage.html");
}
else
{
fclose($fl);
echo "Sorry but the item has already been sold out";
header("Location: oldpage.html");
}
?>
As for the delay, you can accomplish it two different ways. The first is to use PHP header (like you are currently doing), but change it to look like this:
<?php
header("refresh:5;url=oldpage.html");
echo "Sorry but the item has already been sold out";
?>
The other way is to echo out a piece of HTML code, the meta-refresh:
<?php
echo '<meta http-equiv="refresh" content="2;url=oldpage.html">';
echo "Sorry but the item has already been sold out";
?>
In both examples, 5 is the amount of seconds until the refresh. Experiment with each one to see if it will fit your needs.
This might be some sort of syntax that I'm not familiar with, but none of my scripts have ever had the
<? code
I simply use
<?
Also since you did not delay our header tag the user will not see the previously echoed statement above it. It will automatically redirect before the page has time to output fully.

Categories