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]");
Related
I have read many related question here but seems not solve my problem. How to destroy session in PHP when user clicked at the browser back button.
Example, current page is home.php, when back button is clicked, it will go to index.php. So should be session will by destroy.
I trying both options. But still not destroy the session.
First Option (home.php)
<?php
session_start();
if (isset($_SESSION)) {
session_destroy();
}
?>
Second Option (index.php) This is not practical.
<script language="javascript" type="text/javascript">
window.history.forward();
</script>
If you want a reliable way to clear all values of any current session you can use this on the loading of any page where you want to remove session data:
<?php
session_start();
if ($criteria_for_session_deletion === true) {
$_SESSION = []; // _SESSION is now an empty array
}
This will remove any value from the superglobal. It will not change the identity of the superglobal, but that shouldn't be important if the variable is now empty.
It is unclear from your question but you may be having overlap issues with browser caching of the outputted HTML page. Please clarify exactly what you're trying to delete?
Clicking on a "back button" is a very problematical way of solving this concept and we really need some clarification from you as to what's actually going on.
If you have a user who needs to have session data removed then you should check this in PHP on a script before any outout is sent to the browser, and then triggering the above code when required.
You maybe should have a "validity check" script included in each page so every time one of these pages is loaded your "check script" is called, and deletes the session data when the deletion criteria is met.
Why do you want to destroy session? That is just irritating. I have seen such implementations in government/bank websites and it pretty much sucks.
Rather you should redirect the user to dashboard if the user is logged in.
This doesn't directly answer OP's question but is a better way.
Something like this:
if (isset($_SESSION)) {
header('Location: <dashboard-page>');
exit;
}
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.
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">
I have a login form which sends 3 post values from username, password and submit button. But my form processor has 3 pages one is validation.php which validates the field second is read.php which checks the posted values against db and third is login.php which is a result of login success. All redirect to each other respectively on success. Problem here is that when I try to access the user posted values from form in read.php (redirected page) not validate.php (action page) I get an error of undefined index.
I really don't see why you are doing all those redirects, but if you want to make the data more persistent you could use a session variable, because the $_POST superglobal is only set for the current request.
firstfile.php
<?php
session_start();
$_SESSION['posted_data'] = $_POST;
other file
<?php
session_start();
var_dump($_SESSION['posted_data']);
However as already stated you may really want to reconsider doing all the requests.
UPDATE
Besides the fact that you will loose your data you are also doing multiple (unneeded) requests to simply sumbit the form. The only redirect that should happen is to the successpage when you have done all you work. See this for more information: http://en.wikipedia.org/wiki/Post/Redirect/Get
If you are look to keep you code clean you could always just include the other files or go for an OOP approach.
You should do one page only that will do all the work. That doesn't seem too complicated of a script, so I would advise putting everthing together on one page.
You did not provide any code so I'll show you a general example. I just typed it without rereading so it's not pure PHP syntax, just the spirit:
<?php
$login=$_POST['login'];
$pwd=$_POST['pwd'];
$dbcheck = mysql_fetch_array(mysql_query("SELECT COUNT(1) FROM table WHERE user =$login and pwd = $pwd"))
if($dbcheck[0] > 0) {
//Login success
//Setup your session variables, cookies, etc
//Then you can do your redirect here
} else {
//Page for wrong login
}
I might not have known what to search for to get this answer so please point me to the correct post if this has been dealt with already.
Now then, I have a little custom CMS and I want to ensure users don't re-submit their $_POST data by refreshing the page. So I've done something like this:
<?
//Start a session to hold variables I want after my redirect
session_start();
if($_POST){
//Do some php stuff and if I'm happy with the results...
$_SESSION['some_vars'] = $whatever;
//Bring me back here but without the $_POST data
header('Location: '.THIS_PAGE);
exit;
}
?>
When the script reloads I use my session variables and trash the session.
I'm wondering if anybody has a better way to handle this. It's fairly non cumbersome but I'm always looking for more efficiency.
Thanks.
EDIT: By the way, stackoverflow.com does this somehow when you post a question if what I'm doing seems unclear, but they also make a permalink while they're at it.
You have actually implemented what is called the Post-Redirect-Get pattern, and it is absolutely a correct way to do this. I do this myself. I use it so often, I usually implement some minor helper functions into my base controller classes to help me use it:
public function prgRedirect($url = null, $sessionData = null)
{
if ($sessionData !== null) {
if (! isset($_SESSION)) session_start();
$_SESSION['_PRG'] = $sessionData;
}
if ($url === null) $url = $_SERVER['HTTP_REFERER'];
header("Location: ".$url);
}
public function getPrgData()
{
if (! isset($_SESSION)) session_start();
if (isset($_SESSION['_PRG'])) {
$data = $_SESSION['_PRG'];
unset($_SESSION['_PRG']);
}
else {
$data = null;
}
return $data;
}
I usually use it with REST-style URLs, so a POST request will do whatever it has to do, save some data to session using prgRedirect(), which then redirects back to the GET url for the same resource/page. The handler for the GET method will call getPrgData() at the top of the execution and see if there's anything in the session data.
if its important that user dont insert the same data I'm sure there must be some unique column in your database (like headline maybe?). so just check if this headline already exists. you wont need to use any sessions that way
What about:
1. Generate random string (uniqid or md5)
2. Store it in session and put in into hidden input at the form
3. Check form value and session value - if it matches - process the form. Clear the session value.
There are actually two problems here:
users hitting the refresh button in their browser when the data is already saved and you are in a page which saves the data
user hits the "back" button in the browser and clicks "submit" button once again.
In the first scenario, the best scheme is to follow the GET-after-POST pattern where you use the header("location:somewhere_else.php") call to redirect the user. This way you do not have to worry about being called two times consecutively, since the page where you posted the data, is not in the browser's history list (because the server had returned 302 header).
The second scenario hurts a bit more, because the GET-after-POST does not help. If the user submits the form twice, the you may save the data twice. In this case, there may be several solutions:
put a "form identifier" (a random string) in every form you send to the client. When client submits the form, check if you already have such identifier in session data. If you don't have it, save form data and remember the identifier in user's session as "already used". If you find the identifier in session data, don't save anything - it's a duplicate.
check the database for exactly the same values that are submitted. If they match, do not save a duplicate. However, the user may have clicked "back" button, changed some piece of data and then re-submitted the form.