Cant set session variable to stable value on reloading the page - php

I'm making a php app. I used sessions for splitting users
for example:
<?php
session_start();
?>
<?php
$_SESSION["color"] = random_int(1, 2);
?>
I want to became a not changeable and unique value but on refresh it would change its value.
For example:
1,2,1,1,2,1,2,2,1
please help.

PHP session variables are not immutable. You will need to check for the value being set already before setting it to something else. Notice that isset will only work for variables that are not null, array_key_exists maybe more suitable depending on what data is being stored.
if (!isset($_SESSION["color"])) {
$_SESSION["color"] = random_int(1, 2);
}

Related

setting Global variables or application values in laravel 5.3?

I want to assign a value as 0 by default, then every time that page is hit
I want to increase the value by one and when the value is 4 then I have to do some action on that page and change back the value of that variable to 0.
I want to you use global variables or application variables.
I don't want to use the database to save values. I tried my best to save the value in .env but read somewhere it's not the right way to do. Please guide me the best possible way? Working on Laravel 5.3
Thank you very much.
You can create a file in the config folder and store the option there. For example, in a file named system.php:
<?php
return [
"my_option" => 0,
];
Then you can have access to it calling get method from Config:
$myOption = \Config::get('system.my_option');
More info: https://laravel.com/docs/5.2/configuration
You can use session for this:
$counter = (int) session('counter', 0);
session(['error_pages' => ++$counter]);
if ($counter >= 4) {
// here you do what you want
}
Of course in case you want to use this mechanism not in single user session you can use cookies to store counter value.
You can use the config function, is less overhead than use the session:
config(['shared_variable'=>$value])

how to add an array to a session php

I want to add different stuffs to costumers cart but before adding the stuff transition in the database costumer must pay and then redirect to another page after Successful transition i need the chosen stuffs id's i tried using $_POST but the browser does not send the post value because of payment system in the middle i tried using sessions instead
I want to add array of integers to a session control i already tried using this code
$t=array(1,2,3,4,5);
$_SESSION['exam_id']=$t
I don't know if i can do such a thing or not but what is the parallels
What you specified is working correctly. Sessions can hold arrays.
The session superglobal is an represented as an array itself within PHP, so you can just get and set values by doing the following
Setting:
$_SESSION['exam_id'][] = "new value";
or
$_SESSION['exam_id'] = array("new value", "another value");
Getting:
$_SESSION['exam_id'][0]; // returns a value
This returns the first value in the exam_id array within the session variable
You will need to start the session. Make your code;
<?php
session_start();
$t = array(1,2,3,4,5);
$_SESSION['exam_id'] = $t;
You need session_start()
You didn't have a semi-colon ; at the end.
you can use array in session like this..
you have to start session with session_start();
and then store your array to session $_SESSION['items'][] = $item;
and then you use it, whenever you want:
foreach($_SESSION['items'][] as $item)
{
echo $item;
}
You can set PHP sessions equal to an array just like you're doing.
To set the $_SESSION variable equal to all POST data, you can do this:
$_SESSION['exam_id'] = $_POST;
Be sure to add session_start() prior to declaring any session variables.
$t=array(1,2,3,4,5);
$_SESSION['exam_id'] = array();
array_push($_SESSION['exam_id'],$t[0]);
array_push($_SESSION['exam_id'],$t[1]);
array_push($_SESSION['exam_id'],$t[2]);
array_push($_SESSION['exam_id'],$t[3]);
array_push($_SESSION['exam_id'],$t[4]);

PHP undefined index error when clicking a url and invoking a php script

I have a call to a PHP script from my home page which I do like this:
echo 'Delete';
So it is pretty standard.
Then in my PHP I have this code:
<?php
// delete_problem
include '../connect.php'; // Here I have db connection settings
error_log ( ".......in delete problem");
$problem_id = mysql_real_escape_string($_GET["problem_id"]);
?>
And the last line where I try to get the problem_id is throwing the undefined index error. Any idea why?
Thanks!
Have you got an actual connection inside connect.php? Or does it just store variables and the like?
mysql_real_escape_string may be causing a problem as if a connection is not available it will fail.
Beyond that, try echoing out the contents of the GET variable. You can also check whether it exists by using (isset($_GET["problem_id"])).
For values coming from the user, always make sure they are present and possibly validate their format.
Use:
if (isset($_GET['problem_id']) && trim($_GET['problem_id']) != '') {
$problem_id = $_GET['problem_id'];
// make sure it is a number
} else {
echo "No problem id given!";
}
That warning appears because the $_GET array doesn't contain a value problem_id, most likely because it was not passed with the URL.
Bleh, all you people with the mysql_real_escape string...
Always check if a variable is set before you try and assign the value of it to another variable.
Also use (int) to cast!!
if (isset($_GET["problem_id"])){
$problem_id = (int) $_GET["problem_id"];
}

PHP $_SESSION variables not storing values

I'm trying to use PHP session variables to carry data over multiple pages. I am using session variables on many parts of my site, but this is the first place where they don't work.
I'm setting it like this:
$_SESSION["savedRetailerName"] = $foo;
And calling it like this:
echo $_SESSION["savedRetailerName"];
The session id remains the same between these two pages, and I'm sure that I'm setting the variables right and that they are being called right. I start the session correctly, and even on that particular page, other session variables are being shown properly.
How can I begin to debug this odd behavior?
Edit:
There are two different pages I'm currently dealing with. Page 2 sets the session variables, and there is a button that will return the user to Page 1. The idea is to still have the fields in Page 1 filled in if the user wishes to return to Page 1.
It is not a cache problem, and I can return other session variables in the exact same spot in my code as where I am failing to return these variables.
The only other code that may be pertinent is the back button handler (jQuery):
$('#backButton').live('click',function() {
window.location.replace("page 1");
});
Edit 2:
I believe this isn't working because of something with variables here:
<?php
$retailerName = $_REQUEST["retailerName"];
$description = $_REQUEST["description"];
$savingsDetails = $_REQUEST["savingsDetails"];
$terms = $_REQUEST["terms"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$zone = $_REQUEST["zone"];
$dateExp = $_REQUEST["dateExp"];
$tag = $_REQUEST["tag"];
$_SESSION["rn"] = $retailerName;
$_SESSION["de"] = $description;
$_SESSION["sd"] = $savingsDetails;
$_SESSION["tm"] = $terms;
$_SESSION["ph"] = $phone;
$_SESSION["ad"] = $address;
$_SESSION["zo"] = $zone;
$_SESSION["ex"] = $dateExp;
$_SESSION["tg"] = $tag;
?>
I am able to set any session variable to a string, but it won't set to a variable.
You want to use session_start before you set or use any session variables. You only need to call it once.
If it's working in other places, odds are that this particular block of code is being executed before session_start is called.
remove all non printable characters before <?php
you may not see them..
You have spaces before your <php tag
You don't have session_start() anywhere
You are using the $_REQUEST variable which is sketchy (use $_GET or $_POST instead)
You would also need to register the session using
session_register # php.net

PHP/HTML - isset function

I'm fairly new to PHP and am creating a website for my company. I am using some existing code that I have obtained but can't seem to make it work properly - any help would be much appreciated!
I have a variable, $id, which identifies the product category type to display on the page. I first need to check that the id variable has been set and if not, default the variable to category 0.
The code I have is as follows:
setdefault($id, 0);
function setdefault(&$var, $default="")
{
if (!isset($var))
{
$var = $default;
}
}
So with the address www.website.com/browse.php, I would expect it to default to $id=0; with the address www.website.com/browse.php?id=3, I would expect it to set $id to 3 and display the relevant products. However, despite setting $id, it still defaults to 0. Is there something obviously incorrect with my code?
You are probably expecting PHP to use the $_POST and $_GET as global variables. PHP used to be setup this way, back in the day, but newer versions require you to explicitly reference these variables.
You could try this:
setdefault($_GET['id'], 0);
function setdefault(&$var, $default="")
{
if (!isset($var))
{
$var = $default;
}
}
or even more simply (using the ternary operator):
$id = array_key_exists('id', $_GET) ? $_GET['id'] : 0;
First off, if this is PHP 5.X I highly recommend you do not pass variables by reference using the &. That being said. the isset function call will always be true withing the function. But you will receive an undefined variable warning on the setdefault($id, 0);
Try this instead.
$id = isset($id) ? $id : 0;
If $id is not set, the call to setdefault($id,0) will generate a warning. A function like setdefault does not work in PHP. Use this instead.
if (!isset($id)) $id = 0;
If you are doing this for array variables, like $_GET and $_POST, you can do this:
function getuservar($A, $index, $default = '') {
if (!isset($A[$index])) return $default;
if (get_magic_quote_gpc()) return stripslashes($A[$index]);
return $A[$index];
}
$clean_id = getuservar($_GET, 'id', 0);
This return form is better because you stop using the $_GET array immediately and only use the variables that are cleaned in the rest of the code. You clean your external variables once and never touch the external variables again in your code. $A can be $_GET, $_POST, $_REQUEST or $_COOKIE.
It also handles the annoying magic_quote stuff for you so you know the data in the variable is the text sent by the user. Just remember to clean it again when sending it back to the user or to the database.
How is $id being set? If register_globals is off (and it's off by default in PHP 4.2 and newer), you need to look at $_GET['id'] or $_POST['id'] instead (or $_REQUEST['id'], but there are reasons to avoid that).
The code to set $id to sometime from the query string (browse.php?id=3) would also need to be included. You might be thinking of the register_globals settings that PHP has that will automatically create variables when included in the query string. DO NOT re-enable that feature, for several years now that has been shown to be a really bad idea.
Any variable you are pulling from the query string needs to be checked for type/safety before using it. So for example you might pull the variable from the $_GET super global, check to see if it's numeric, if it is not then set the default:
if (!is_numeric($_GET['id']) {
setdefault($_GET['id'], 0);
}

Categories