I am just trying to write a function in php that adds to the discount array but it doesn't seem to work at all.
function addToDiscountArray($item){
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Every time I refresh the page it acts like $_SESSION["discountCalculator"] hasn't been set up but I can't understand why. Whilst writing can I use the $_SESSION["discountCalculator"] in a foreach php loop in the normal way too?
Many thanks
The fact that every time $_SESSION['discountCalculator'] seems not to be set, could be because $_SESSION is not set (NULL). This case happens mostly when you did not executed session_start() at the beginning of you page.
Try adding session_start() at the beginning of the function.
function addToDiscountArray($item) {
if (!$_SESSION) { // $_SESSION is NULL if session is not started
session_start(); // we need to start the session to populate it
}
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Notice that this will not affect the function if the session is already started. It will only run ´session_start()` if the session is not started.
Related
[PHP 7.1]
Below you can see my PHP code. My problem comes from my difficult to understand why the second IF statement doesn't work with the array $_SESSION['items'], but does work with the testing array $zoo (I just created $zoo to make tests in place of $_SESSION['items']).
I've an AJAX script that send POST data to the PHP code and then logs the response to the browser console in order to let me review the results. Everything was working fine with my tests, all changes done to other arrays where executed with fine results, the only issue I couldn't understand and solve, even after extensively searching for some clues on the web and trying different things, is the misterious ways of the $_SESSION array that doesn't seem to like to expose its keys to lurking IF statements... And I got here trying to detect the existence of a key inside an array in order to increment its value. Something I already did before with other arrays that weren't $_SESSION arrays and it worked just fine.
session_start();
$_SESSION['items'] = array();
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['item_name'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
This is a simplified version of your code with just the important stuff
session_start();
$_SESSION['items'] = array(); //items is now emtpy
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
}
This should make it a bit easier to see, so it's simply because items is an empty array. Do to assigning it as such before the condition.
To fix it, either remove this line:
$_SESSION['items'] = array();
OR better yet:
$_SESSION['items'] = isset($_SESSION['items']) ? $_SESSION['items'] : [];
OR even
if(!isset($_SESSION['items'])) $_SESSION['items'] = [];
It's up to you how you fix it, but I am certain you don't want to reset that to an empty array. It's a very easy mistake to make, and a hard one to find because it's technically legal PHP code. I just have a built in debugger in my head now, from years of coding ... lol ... Most times I can literally picture in my mind how something will execute.
Cheers!
As noted by #artisticphoenix -
session_start();
// Check to see if there is a session variable before clearing it
// You only want to initialize it once
if (!isset($_SESSION['items'])) {
$_SESSION['items'] = [];
}
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
// This test is sufficient to check if the session variable has been set
if (isset($_SESSION['items'][$_POST['item_name']])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['items'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
$_SESSION['item_name'] should be $_SESSION['items']
I am trying to add new items to my array if they don't already exist but below code shows me an error:
// Check if session exists
if(!isset($_SESSION['coupon'])){
// Create array from session
$_SESSION['coupon']['couponcode'] = array();
}
if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
// Add couponcode to session if it does not already exist
$_SESSION['coupon']['couponcode'][] = $coupon;
}
$_SESSION['coupon']['couponcode'][] = $coupon;
Gives: PHP Fatal error: Uncaught Error: [] operator not supported for strings
But I thought this was the way to add to the array, if I remove the brackets it just replaces the value everytime.
I have session_start(); everywhere at the top of my pages.
You can use array_push():
if(empty($_SESSION['coupon'])){
// Create array from session
$_SESSION['coupon']['couponcode'] = array();
}
else
{
if(!in_array( $coupon,$_SESSION['coupon']['couponcode'])) //check in array available
{
array_push($_SESSION['coupon']['couponcode'], $coupon); //push to array
}
}
First of all,do not put blindly session_start() on top of every page. It will start session again even if a previous session was running and will refresh your all values, so first thing, change that to:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
this way it starts the session only if it doesn't exist.
Now, you are getting error because somehow your $_SESSION['coupon']['couponcode'] is a string so add an additional check:
if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
// Add couponcode to session if it does not already exist
if (empty($_SESSION['coupon']['couponcode']) || !is_array($_SESSION['coupon']['couponcode']))) {
$_SESSION['coupon']['couponcode'] = [];
}
$_SESSION['coupon']['couponcode'][] = $coupon;
}
I was wondering how i could retrieve the last instance in the Session named smartBacklinks.
Here is the code
if(Session::has('smartBacklinks'))
{
// if(Request::header('referer') === LAST ITEM IN SESSION[smartBacklinks] ARRAY)
Session::push('smartBacklinks', Request::header('referer'));
}
else
{
Session::put('smartBacklinks', [Request::header('referer')]);
}
Also how do i retrieve this from a blade template ?
You can retrieve 'smartBacklinks' from the session based on the key like so:
$value = Session::get('smartBacklinks');
Also, you may want to note that you'd use Session::push() for pushing into an array session value and use Session::put() to simply store an item in session.
Retrieving the value from blade:
I guess you could pass the variable just retrieved to the view from the controller like so:
return View::make('foo.bar', array('smartBacklinks' => $value));
then use it in blade like so:
Go back
Hope that helps.
I edited my code alot and it is now functioning. I still need to add a few tweaks to make it behave 100% as i need it
The code looks like this right now:
if(Session::has('smartBacklinks')){
// Get the last item in Session array
$slice = array_slice(Session::get('smartBacklinks'), -1, 1);
// Check if Request::header('referer') is equal to the $slide[0]
if(Request::header('referer') != $slice[0]){
// Check if Request::header('referer') is empty
if(Request::header('referer') != '') Session::push('smartBacklinks', Request::header('referer'));
}
// If session[smartBacklinks] is not set. - Set
}else {
Session::put('smartBacklinks', [Request::header('referer')]);
$slice = array_slice(Session::get('smartBacklinks'), -1, 1);
}
Session::save();
Then of course the last instance of the session array is
$slice[0]
The last thing i need to add is:
when "back button" is clicked, it should remove the last instance of the session array, and it should not push URL into the session
I need to make sure that the session is loaded correctly so i dont have to refresh the webpage to get the correct "back URL"
Thanks for the answer!
I'm trying to pass a value between 2 pages through a $_SESSION variable then empty it as follows:
I'm assigning the session variable with a value on one PHP page:
$_SESSION["elementName"]="a_373";
And trying to store it in a variable on another page as follows:
if (!empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
The value of $elemName is always empty when I print it out. However, I get the correct printout when I remove the $_SESSION["elementName"]=""; line from the above code.
Edit: I'm printing $elemName and not $_SESSION["elementName"] - print($elemName);
I'm on a shared hosting account with PHP 5.3.2 and register_globals set to off (as per phpinfo();).
I need to reset/empty the session variable once I get the value it has, but it's not working and this has been baffling me for the last couple of days. Any ideas why? Thanks!
EDIT:
Additional clues: I tested with the session's var_dump before the if statement and set another value for $elemName in the else section as follows:
var_dump($_SESSION["elementName"]);
$elemName="x";
if (isset($_SESSION["elementName"]) && !empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="None";
}
print("<br />".$elemName);
I got this result:
string(5) "a_373"
None
Try using isset($_SESSION["elementName"]) and unset($_SESSION["elementName"]) instead.
Check the Below code and test it
if (isset($_SESSION["elementName"]) && $_SESSION["elementName"]!="") {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
Empty only check value is empty or not, But by isset we can check varaible exit and does not content empty value
Are you printing out $elemName? If yes than there shouldn't be any blank output unless and until your else condition returns true, but if you are printing $_SESSION["elementName"] than you'll get no output as you are making it blank
$_SESSION["elementName"]="";
Correct way to remove a session var completely is to use unset($_SESSION["elementName"])
Though if you want to make it empty, == '' is enough
Also be cautious while using unset() because after you unset the session and later use that index to print, it will show you undefined index error.
Update(As #nvanesch Commented)
I guess your else condition is getting satisfied, because you are
using $elemName=""; in your else, thus you are not returned with any
output
Also if (!empty($_SESSION["elementName"])) { will return false if you are not using session_start() at the very top of your page
I once created this class in order to be able to have this ability, and it works wonderfully:
<?php
class Flash {
public function set($key, $message) {
$_SESSION["flash_$key"] = $message;
}
public function get($key) {
$message = $_SESSION["flash_$key"];
unset($_SESSION["flash_$key"]);
return $message;
}
public function has($key) {
return isset($_SESSION["flash_$key"]);
}
}
It's pretty similar to what you're trying to do, so I'm not sure why it's not working for you, but you may want to give it a try. You obviously need to have the session already started.
public function action_adicionar_item()
{
$lista_item_pedido = array();
$x = 0;
if(Session::has('lista_item_pedido'))
{
foreach(Session::get('lista_item_pedido') as $item)
{
$lista_item_pedido[$x] = $item;
$x++;
}
}
$lista_item_pedido[$x] = Input::all();
Session::put('lista_item_pedido', $lista_item_pedido);
}
The first time I ran this method, the session is not created so the if is ignored and it sets the array value and should define the session with name a value but it doesn't.
The second time I call it, the session is created but with no values, what is weird.
Any ideas why on my first run the session is created with the empty array?
Input::all() is returning the correct values.
I have checked the file storage/sessions/ the file is created and the value is set correctly:
s:17:"lista_item_pedido";a:1:{i:0;a:7:{s:2:"id";s:3:"162";s:10:"referencia";s:12:"112233445566";s:9:"descricao";s:6:"Sapato";s:5:"grade";s:14:"Grade 41 ao 46";s:8:"grade_id";s:1:"4";s:5:"valor";s:5:"50.00";s:10:"fornecedor";s:2:"30";}}}s:13:"last_activity";i:1340395110;}
This is created the first time I run the method, so it is created but I can't access it, only when I add two values and in this case, the first is ignored.
Try using $_SESSION instead...