Weird SESSION issue on PHP - php

I'm having a very weird SESSION problem, I've been working with sessions in my server for a long time and everything working fine. I've searched & tried a lot of changes for 5 hours before posting this question.
Anyway, it seems that $_SESSION is not updating correctly. I have a form using POST that goes to the same page and when the user submits the info its saved in $_SESSION and then I do some stuff and update the session variable. Everything looks good in the page cause when I'm done I save the session with the new variables and then do a var_dump($_SESSION["whatever"]); and it shows the updated data. But when I submit the form again with new settings and show the data of $_SESSION in the reloaded page it's still the old data.
My code is kind of complex and I do a lot more than just save the data but I'm resuming the situation here:
session_start();
var_dump($_SESSION["whatever"]);
if(isset($_POST["whatever"])){
$_SESSION["whatever"]=$_POST["whatever"];
} else {
$_SESSION["whatever"] = FALSE;
}
var_dump($_SESSION["whatever"];
So, the below var_dump does show the new value entered in the form, that should mean it has been saved correctly, but no! Because when I enter the form again the first var dump that should have the same value as the last var_dump in the previous page still shows the original value (FALSE).
Any ideas?
UPDATE: Even if I go to a new page and just do this:
session_start();
var_dump($_SESSION["whatever"]);
It shows the old data, not the updated one.
PS: By the way I have many other variables that are not inside this if/else statement that do save correctly, and the session does update from the values on other previous page.
NEW UPDATE: I'm using jQuery to display the form with sliders and knobs, if I eliminate jQuery everything works well! It is very weird! I have seen nothing like this on the internet, any ideas?

session_start();
var_dump($_SESSION["whatever"]);
if(isset($_POST["whatever"])){
$_SESSION["whatever"]=$_POST["whatever"];
} else {
// Check if there is a session variable set
if (!isset($_SESSION['whatever'])) {
// If the session variable isn't set, initialize it to false
$_SESSION["whatever"] = FALSE;
} else {
// Set the $whatever variable to be the value of the session variable
$whatever = $_SESSION['whatever'];
}
}
var_dump($_SESSION["whatever"];
<!-- In the HTML -->
<input name="whatever" value="<?php echo $whatever ?>" type="text">

Related

php $_POST variable is not saving

I currently have some php code on a form action, and it is being updated to the form's next page with
<?php echo $_POST['var here']; ?>
and it is working, but I noticed when Im trying to refresh the page it asks to confirm resubmission. When I resubmit it works in that tab in which it was sumbitted, but in another new tab it does not show the displayed php post variables. I even took it the next step by seeing that when I open the 2nd page after the form action has been submitted the php post variables are gone...
Help!
Thanks!
When you submit a form with <form method="post" /> it does a post request to the server, thus populating $_POST. When you open the link in a new tab it is no longer a post request but a get request. That is why you'll see nothing in $_POST.
$_POST — usually from forms
$_GET - from values on the URL (the query string myscript.php?myvar=Joe)
You can find plenty of resource about it. You can start here
If you want to keep the values you can save them to the session:
<?php
session_start(); // should be at the top of your php
if (isset($_POST['var'])) {
$_SESSION['var'] = $_POST['var'];
}
$myvar = isset($_SESSION['var']) ? $_SESSION['var'] : "no var";
echo $myvar;
Now the value is stored in the session so you can visit the page in a new tab and it will still be there.
This sounds like desired behavior. The $_POST variable should only be filled when the post action is created. If you're looking to store variables across pages you could store it in either the $_SESSION var in PHP or deal with the front end $_COOKIE business. If you're always going to be rendering pages from the backend then $_SESSION is the way to go. It's never too late to read up on cookies and sessions.
The skinny of it is that you're going to want to do something like this:
<?php
session_start();
if ($_POST['var']) {
$_SESSION['var'] = $_POST['var'];
}
echo $_SESSION['var'] ?: $defaultValue;
Then you'll notice that the message changes only when you post and won't exist before then.

Dump php variables gotten from POST

I have some PHP code running at the top of my page
if(isset($_POST['arrow1']) and isset($_POST['arrow2'])) {....}
And a form that sends data to this page. What i want to do is to empty the variables once the php code at the top runs so that on refresh it won't run again.
How can i achieve that?
Thank you
I know the question is a little bit outdated but....
Your form will run only once... or everytime... depending on how you load the page. If the form submits POST, unsetting is kind of sinceless. Let´s say the form on the top says:
Push button and submit "hello world". You push the button, page get´s load (and since you dont use ajax, it has to load new), "hello world" is submitted and after submit POST get´s unset. Form is still there.. you press button again... same thing happens again. To avoid this you propably have to use $_SESSION
Sample
if((!isset($_SESSION['arrowsWasSet']))
{
if(isset($_POST['arrow1']) and isset($_POST['arrow2']))
{
unset($_POST);
$_SESSION['arrowWasSet'] = true;
}
}
other way is to store data into the session and check if its already set to session.
if(isset($_POST['arrow1']) && isset($_POST['arrow2']))
{
if(!isset($_SESSION['arrows']))
{
$_SESSION['arrows']['arrow1'] = $_POST['arrow1'];
$_SESSION['arrows']['arrow2'] = $_POST['arrow2'];
}
unset($_POST);
//you can call this to get a clean post everytime, but no need.
}
do you have a type in there ? i mean shouldnt this mean array1 instead of arrow1 ? :)
anyways, $_SESSION survives the refresh. So after refreshing the page, you can still check if something happend. To empty session you could do:
session_destroy (kills hole session)
restart your Browser (not refresh, totaly restart! kills hole session)
hitting keys ALT + F5 (kills hole session)
clear Browsercache manualy (kills hole session)
$_SESSION['xy'] = NULL; (kills parts in session)
unset($_SESSION['xy']); (kills parts in session)
if(isset($_POST['arrow1']) and isset($_POST['arrow2']))
{
unset($_POST);
}
Will unset all $_POST variables.
You could also do:
$_POST['arrow1'] = NULL;
$_POST['arrow2'] = NULL;
You can simply redirect the user on the same page.
In this case, after the script execution, if he wants to refresh the page, there is no more variable in the header...
<?php
header("location:[your/path.php]");

use session cookies per specific browsertab

I currently have a form that allows a user to edit entries. However, it doesn't seem to be possible to use 1 (specific) cookie per tab. Whenever a user edits an entry, the record in the last tab gets updated.
I've tried the following in my main script (eventfilters.php):
<?php
$cookie_name = $_SESSION['username'].md5(time());
session_name($cookie_name);
setcookie(session_name($cookie_name),session_id(),time()+"300");
if(!isset($_SESSION)){ session_start(); }
if (isset($_GET['edit'])){
// Pass cookiename in url variable $cookie, so it gets caught by $_GET['cookie']
echo '<form action="eventfilters.php?save&cookie='.session_name().'" method="post">';
} else if (isset($_GET['save'])){
if(isset($_GET['cookie'])){
error_log("SAVE ".$_GET['cookie']); // Displays cookie url variable set by form action.
error_log("LOW ".$_SESSION['level_low']);
// Displays correct session value received from ajax
}
}
?>
`
The ajaxcode (also in eventfilters.php) contains this (called few times when page is already loaded):
$.post("include/severitygroups.php",{'cookie_name': "<?php echo $cookie_name; ?>", 'serialized_sev_groups': serialized_sev_groups}, function(data){});
This seems to pass the right cookiename to the other script, which successfully seems to return $_SESSION['level_low'] (as it appears in the error_log).
<?php
include('pdodb.php');
if(!isset($_SESSION)){ session_start(); }
$cookie_name = $_POST['cookie_name'];
error_log("SCRIPT ".$cookie_name);
error_log("COOKIEDATA ".$_COOKIE["$cookie_name"]);
// populating $_SESSION['level_low']
?>
It seems that the $_GET['save'] is populating the wrong sessions (initialised by the last loaded instance of eventfilters.php), even when the $_GET['save'] logs the right $_SESSION['level_low'] to the errorlog.
What is going wrong?
You can't do it. The best way to do it, is with Ajax, so, you will pass an "ID" to each tab (or page) like:
editPost.php?id=someID
And, each time you press save, you should send your content with your id param to save it.

Unset POST values in php

acitvity.php
//Form start
<form action=''>
</form>
//Form End
//Get POST Values
<?php
$_POST[''];
?>
//End
if i refresh the page after form is submitted, all the posted values are resubmitted, reason because all values are in browser so they are resubmitted. When i was searching solution for this, i got info that if the form & post operation done in separate php file then no more issue in posting values on refresh.
Is this the solutions? but now i have to do both in single file & POST values should not be submitted again on refresh.. is there any way to do this???
Learn PRG Pattern so that you can do this properly :)
http://en.wikipedia.org/wiki/Post/Redirect/Get
For example, you are trying to handle a user registration form, so what you do is you get a bunch of POSTed values, and save it into your database.
if(!empty($_POST)) {
// validate and save to db
// get last inserted user_id
}
After you do that, instead of returning the same page with the previously POSTed values, you redirect the new user, for example to his profile page (assuming you have no activation requirement in place)
if(!empty($_POST)) {
// validate and save to db
// get last inserted user_id, say in $user_id
header("Location: /users/$user_id");
}
That way, the browser redirects and you won't have problem with say, double registration, whenever the user hits refresh.
After saving to your database, reload your page:
if ($_POST) {
// Save $_POST to database and other stuffs
// Reload current page to discard $_POST
header('Location: my_page.php');
}
That's called PRG or Post/Reload/Get
You can use unset($var) to unset a variable. However, I think the issue is with the browsers; some of them try to be smart and will remember form data regardless when you refresh the page. If you hit "go" or "enter" on the URL bar it does a "true" refresh though.

PHP Saving Session Variable

I am trying a new CAPTCHA Script from here. To call the CAPTCHA code you use: $_SESSION['captcha']['code']
Well that works when I echo it out on the main form, but when I echo it after the form has been submitted, it displays a new code so I can never find out what the old code was when they submitted the form.
if($_POST['submit']) {
echo $_SESSION['captcha']['code'];
}
How can I save that session data and not make it change any more?
You should store it in your own SESSION variable:
$_SESSION['old_captcha'] = $_SESSION['captcha'];
Then, when the form is submitted, use you own variable:
if($_POST['submit']) {
echo $_SESSION['old_captcha']['code'];
}
Put that BEFORE you include the captcha.php again on the next step.
My guess is that it displays a new code because you come back to the page that displays it. Try submitting to a different page, or maybe not executing the captcha creation code if the session variable is already set.

Categories