Variable should not return to default value - php

<?php
$transVar = "000000001";
$transF = (1+ $transVar);
echo "<br>";
echo $transF;
?>
I need the output of the code to be 0000000002 and be incrementing on refresh even closing and reloading the script, I don't seem to be getting it, Any help?

This should do the trick:
if (isset($_SESSION["TransVar"])) {
$_SESSION["TransVar"] += 1;
} else {
$_SESSION["TransVar"] = 1;
}
echo str_pad($_SESSION["TransVar"], 8, '0', STR_PAD_LEFT);
When the page loads the first time we set the session value to 1, then increment it after each page refresh. We keep the session value as a number, and pad it with zeroes instead of saving the value as a string.
Keep in mind that this value is only persisted as long as the session is alive, so it won't be stored forever. If you need to persist this value indefinetely, then you need a different approach.
Read more about PHP sessions: https://www.php.net/manual/en/intro.session.php

Related

How to access increment value of session on same page in php

How to access the incremented value of session on the same page where we have defined the initial value of session, I am using this method for incrementation of value but on another page
<?php
$_SESSION['indexValue'] = 1;
?>
This is my test.php page where i have decrelaed the inital value of session.
<?php
$Incrementvalue = $_SESSION['indexValue'];
$counter = (int)$Incrementvalue;
if ($counter=$counter) {
$counter++;
$_SESSION['indexValue'] = $counter;
}
echo "$_SESSION['indexValue']";
?>
This is my getdata.php page where I have implmented the increment value function. Now i have to pass this increment value of Session again on test.php page . How can I perform this?
your code seems not to be thought off
first of all, you need to call session_start() at beginning
then you can access everyewhere your $_SESSION variable (if you call session_start() before)
if ($counter=$counter) {
$counter++;
$_SESSION['indexValue'] = $counter;
}
this seems useless
$_SESSION['indexValue']++;
is enough
First of all there are few errors in code like
if ($counter=$counter) should be if ($counter == $counter)
And
echo "$_SESSION['indexValue']" should be echo $_SESSION['indexValue'].
Now answer to your question is that session is accessible anywhere throughout the project/application. So you need not to pass it , just access it as $_SESSION['indexValue'].

PHP Session Variable - change on page load

I'm trying to get a session variable to alternate between 0 and 1 on each page load.
So first time page loads
$_SESSION['turn'] = 0;
Second time
$_SESSION['turn'] = 1;
Third time
`$_SESSION['turn'] = 0;`
and so on.
Then I can call that variable later in the page.
I can't work out how to do this. I've tried a simple IF function but can't get it to work.
First the session must be started on any page wishing to make use of the session array. session_start()
Next you have to remember that initially the session variable you are using will not exist the first time you attempt to use it
So
<?php
session_start();
if ( !isset($_SESSION['turn']) ) {
// does not exist yet, so create with 0
// you may want to initialize it to 1, thats up to you
$_SESSION['turn'] = 0;
} else {
$_SESSION['turn'] = $_SESSION['turn'] == 0 ? 1 : 0;
}
Try this where the page is loaded.
$_SESSION['turn']=1-$_SESSION['turn'];
code:
<?php
session_start();
echo $_SESSION['turn'];
$_SESSION['turn']=1-$_SESSION['turn'];
?>
Edit : RiggsFolly !isset() is correct. mine misses it and it will give errors in log. and the first value is not 0

Incrementing the value of the post by every repeated form submission

I have a form sender which is posting a value of 6 to another form receiver. What I'm trying to achieve is store the posted value from sender into a variable in the receiverthen increment the variable it every time the sender posts. Then print the updated variable
This is what I have tried to do
$val= $_POST['val'];
$limit = 6 + $val;
echo $limit;
Im getting the result as 12. But what I want is
After first post result = 12
After second post result = 18
On and on...
NB:$_POST['val'] = 6;
session_start();
$limit = 6;
if(!isset($_SESSION['lastLimit'])) {
$_SESSION['lastLimit'] = 0;
}
if(!empty($_POST)) {
$_SESSION['lastLimit'] = $_SESSION['lastLimit'] + $limit;
$postedValue = $_POST['val'] + $_SESSION['lastLimit'];
echo $postedValue;
}
Because the web is stateless i.e. scripts do not remember anything that happened the last time a page/form was executed the receiver script does not remember anything from the last time it was run.
But dont panic, there is a way. Its called a SESSION and you can store data in the session which will then be available the next time this user connects to your site. In PHP you use it like this. The session is linked to this specific connection to a specific user.
receiver.php
<?php
// must be run at top of script, before any output is sent to the new form
session_start();
// did the form get posted and is the variable present
// or replace POST with GET if you are using an anchor to run the script
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['val']) {
if ( isset($_SESSION['limit'] ){
// increment the limit
$_SESSION['limit'] += (int)$_POST['val'];
} else {
// initialize the limit
$_SESSION['limit'] = (int)$_POST['val'];
}
echo 'Current value of limit is = ' $_SESSION['limit'];
} else {
// something is not right
// direct this user to some basic page like the homepage or a login
header('Location: index.php');
}
You need an intermediate layer to store the value.
Available options:
1) Global static value
2) session
3) file
4) database
I would recommend global value or session, as they data you want to store isn't that huge and would meet the requirements easily.
I would not write the syntax to store it in session as a number of people have already mentioned it. I just wanted to clarify the problem scenario and possible solutions.
You can store $limti into global varibale .
global $val;
$val += $_POST['val'];
$limit = 6 + $val;
echo $limit;

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

Very strange $_SESSION behaviour

I have a Session which I am using to hold items in a form that are accumulated up by the user until the user wants to proceed to checkout. Its a bit like a Shopping cart where items can be added from the form.
Logical breakdown of code:
Page loads, session starts
If $_SESSION['set'] is not set then set it to TRUE.
Display rest of page and form.
User hits "Add another item" button.
Page data gets posted to itself
Page checks that $_SESSION['set'] = True and $_POST['add_item'] is set.
Page creates a session variables in an array, and adds posted values to those sessions.
Page increments $_SESSION['tariff_count'] if more needs to be added
The problem is that my code is not behaving as it should. When I click "Add new tariff" button the first time it does not get caught by my if function. This should be immediately caught. However when I go and press the button again, it finally works and adds an item to my session.
Here is the code:
//start a session to remember tariff items
session_start();
//testing the session array
print_r($_SESSION);
//destroy session if this character is found in URL string
$des = $_GET['d'];
if($des == 1)
{
session_destroy();
}
//checks to see if session data has been set
//if a session variable count is set then
if ($_SESSION['set'] == TRUE)
{
//perform a check to ensure the page has been called by the form button and not been accidently refreshed
if(isset($_POST['add_tariff']))
{
//if user clicks Add another tariff button then increase tariff count by one
//temp variable set to the current count of items added
$count = $_SESSION['tariff_count'];
$_SESSION['tariff_name'][$count] = $_POST['tariff_name'];
$_SESSION['tariff_net'][$count] = $_POST['tariff_net'];
$_SESSION['tariff_inclusive'][$count] = $_POST['tariff_inclusive'];
$_SESSION['tariff_length'][$count] = $_POST['tariff_length'];
$_SESSION['tariff_data'][$count] = $_POST['tariff_data'];
//increment tariff count if more data needs to be added to the sessions later.
$_SESSION['tariff_count']++;
}
}
//if no session data set then start new session data
else
{
echo "session set";
$_SESSION['set'] = TRUE;
$_SESSION['tariff_count'] = 0;
}
The code seems to be fudging my arrays of Sesssion data. All my added items in the session are displayed in a table.
However if my table shows six items, if i do a print_r of the session it only shows there are 4 items in the array? I have tested it to make sure I am not reprinting the same instances in the array.
Here is a print_r of the array that shows six rows but there are only four rows in this array?
[tariff_count] => 5 [tariff_name] => Array (
[0] => STREAM1TARIFF [1] => STREAM1TARIFF [2] => CSS [3] => CSS [4] => CSS
)
I have take a screenshot as well to show this strange problem
http://i.imgur.com/jRenU.png
Note I have echoed out "True Value =6" but in the print_r of the session it is only 5, so my code is missing out one instance (n-1).
Here is my code that prints all the instances in the session arrays, I have a feeling part of the problem in mismatch is caused by the "<=" comparison?
if(isset($_SESSION['tariff_count']))
{
for ($i = 0; $i <= $count; $i++)
{
echo "<tr>";
echo "<td>".$_SESSION['tariff_name'][$i]."</td>";
echo "<td>".$_SESSION['tariff_net'][$i]."</td>";
echo "<td>".$_SESSION['tariff_inclusive'][$i]."</td>";
echo "<td>".$_SESSION['tariff_length'][$i]."</td>";
echo "<td>".$_SESSION['tariff_data'][$i]."</td>";
echo "</tr>";
}
}
Paste bin of php page - http://pastebin.com/petkrEck
Any ideas, why my If statement is not catching the event when the user presses "Add another tariff" button the first time it is pressed, but then detects it afterwards?
Thanks for your time
Merry Christmas!
The problem is your code flow. In simplified pseudo-code, you're doing this:
if (session is not initialized) {
set = true
count = 0;
} else {
add posted data to session
}
On the first 'add item' call, the session is not set up, so you set up the session. AND THEN IGNORE THE POSTED DATA.
The code flow should be:
if (session is not initialized) {
set = true;
count = 0;
}
if (posting data) {
add data to session
}

Categories