Sorry if this is a duplicate, but I really cant find anything that could solve my problem. I can pass numbers and strings like $_SESSION['blabla']="123'; but I can't pass this $_POST value from the textfield and submit button.
Page 1 (sessions.php)
<?php session_start(); ?>
!doctype stuff here
<body>
<form id="form1" name="form1" method="post" action="sessions2.php">
<label>
<input type="text" name="damn" id="damn" />
<input type="submit" name="submit" id="submit" value="Submit" />
</label>
</form>
<?php
$omg = $_POST['damn'];
$_SESSION['damn'] = $omg;
echo $_SESSION['damn'] ;
?>
Page 2 (sessions2.php)
<?php
session_start();
$fires = $_SESSION['damn'];
echo "wth";
echo $_SESSION['damn'];
?>
PS. Sorry for the names.. I'm truly stumped.
You need to put the code that reads from $_POST in the file that you submit the form to.
Currently your process is:
Get request for sessions.php
Send form to browser
Assign $_POST['damn'] (which is undefined) to the session.
User submits form
Get request for sessions2.php
Ignore $_POST (which is now populated)
Read from the session (where the variable is still undefined).
damn is populated in the form submission request (step 4/5) not the request where you are trying to read it (step 1).
In sessions2.php
// you POST "damn" variable via form, using post method, so:
$fires = $_POST['damn'];
// and:
$_SESSION['damn'] = $fier;
// or
$_SESSION['damn'] = $_POST['damn'];
PHP code in file sessions.php doesn't work, because in form action you have session2.php.
Related
I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.
I'd like to know how to correct this behavior, for example, when I have a block of code like this :
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
die();
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.
How this problem can be avoided? Any suggestion will be appreciated :)
Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.
// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is an example:
<?php
session_start();
if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
echo 'Process form';
}
else
{
$_SESSION["formid"] = md5(rand(0,10000000));
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
<input type="submit" name="submit" />
</form>
<?php } ?>
I ran into a similar problem. I need to show the user the result of the POST. I don't want to use sessions and I don't want to redirect with the result in the URL (it's kinda secure, I don't want it accidentally bookmarked). I found a pretty simple solution that should work for the cases mentioned in other answers.
On successfully submitting the form, include this bit of Javascript on the page:
<script>history.pushState({}, "", "")</script>
It pushes the current URL onto the history stack. Since this is a new item in history, refreshing won't re-POST.
UPDATE: This doesn't work in Safari. It's a known bug. But since it was originally reported in 2017, it may not be fixed soon. I've tried a few things (replaceState, etc), but haven't found a workaround in Safari. Here are some pertinent links regarding the issue:
Safari send POST request when refresh after pushState/replaceState
https://bugs.webkit.org/show_bug.cgi?id=202963
https://github.com/aurelia/history-browser/issues/34
Like this:
<?php
if(isset($_POST['uniqid']) AND $_POST['uniqid'] == $_SESSION['uniqid']){
// can't submit again
}
else{
// submit!
$_SESSION['uniqid'] = $_POST['uniqid'];
}
?>
<form action="page.php" method="post" name="myForm">
<input type="hidden" name="uniqid" value="<?php echo uniqid();?>" />
<!-- the rest of the fields here -->
</form>
I think it is simpler,
page.php
<?php
session_start();
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
$_SESSION["message"]="Operation Done";
header("Location:page.php");
exit;
}
?>
<html>
<body>
<div style='some styles'>
<?php
//message here
echo $_SESSION["message"];
?>
</div>
<form action='page.php' method='post'>
<!--elements-->
</form>
</body>
</html>
So, for what I needed this is what works.
Based on all of the above solutions this allows me to go from a form to another form, and to the n^ form , all the while preventing the same exact data from being "saved" over and over when a page is refreshed (and the post data from before lingers onto the new page).
Thanks to those who posted their solution which quickly led me to my own.
<?php
//Check if there was a post
if ($_POST) {
//Assuming there was a post, was it identical as the last time?
if (isset($_SESSION['pastData']) AND $_SESSION['pastData'] != $_POST) {
//No, Save
} else {
//Yes, Don't save
}
} else {
//Save
}
//Set the session to the most current post.
$_session['pastData'] = $_POST;
?>
We work on web apps where we design number of php forms. It is heck to write another page to get the data and submit it for each and every form. To avoid re-submission, in every table we created a 'random_check' field which is marked as 'Unique'.
On page loading generate a random value and store it in a text field (which is obviously hidden).
On SUBMIT save this random text value in 'random_check' field in your table. In case of re-submission query will through error because it can't insert the duplicate value.
After that you can display the error like
if ( !$result ) {
die( '<script>alertify.alert("Error while saving data OR you are resubmitting the form.");</script>' );
}
No need to redirect...
replace die(); with
isset(! $_POST['name']);
, setting the isset to isset not equal to $_POST['name'], so when you refresh it, it would not add anymore to your database, unless you click the submit button again.
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
isset(! $_POST['name']);
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">
I think following is the better way to avoid resubmit or refresh the page.
$sample = $_POST['submit'];
if ($sample == "true")
{
//do it your code here
$sample = "false";
}
So here's my full code
<!DOCTYPE html>
<html>
<body>
<h1>Encrypt</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter word to encrypt<input type="text" name="in">
<input type="submit">
<hr>
</form>
<h1>Decrypt</h1>
<form>
Enter word to decrypt<input type="text" name="out">
<input type="submit">
<hr>
</form>
</body>
</html>
<?php
$encrypt = $_POST['in'];
?>
And here's the error I get
Notice: Undefined index: in in /Users/idrisk/Colourity/si/index.php on line 20
Line 20 is $encrypt = $_POST['in']; and I don't see what I'm doing wrong with it. Any ideas?
As a general practice for forms in php, always check if the submit button has been clicked.
First name your submit button:
<input type="submit" name="submit">
then further in your php:
if (isset($_POST['submit'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
EDIT #1: Added to that, you seem to have 2 forms and 2 submit buttons. I suggest you keep only one form, and one submit button (remove the 2nd form element and submit button).
If you really need 2 forms, name your submit buttons differently and then you can call them separately.
<input type="submit" name="submit-in">
<!-- ... -->
<input type="submit" name="submit-out">
<?php // ...
if (isset($_POST['submit-in'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
if (isset($_POST['submit-out'])) {
// do your stuff, eg...
$dencrypt = $_POST['out'];
}
EDIT #2: If you want to echo stuff posted in your form, make sure you do the form submission checking and variable setting before the form and then echo the variable after the form (or wherever you want).
you need to first check if the form has been sent, if it hasn't then $_POST['in'] does not yet exist thus throwing the error
May be nothing but you called a php script after closing the form /form, the body /body and then then the HTML /html
replace this code $encrypt = $_POST['in']; by this $encrypt = #$_POST['in'];
this is an error on client server when you upload this file on remote server you will not saw this. use # sign on the client server when you saw this error in future.
I have a php form that at the moment posts the data to a Paypal cart, but I want to post the data to a new php page almost like a confirmation page which shows the options and selections you selected to and from that point for you to be able to send on to Paypal?
Is this possible?
Someone new to session or post may find this example helpful. complete example of what you want. how to Store and view post array into a session named POSTDATA.post or anyother variables are accessible to a same session, from any page if its stored in a session variable.
form.php
<?php
//PHP content of form.php file
session_start();
if ($_POST)
{
$_SESSION['POSTDATA']=$_POST;
}
?>
<html>
<head></head>
<body>
<form action="form.php" method="post">
<input type="text" name="hello"/>
<input type="submit" name="submit" value="submit"/>
</form>
<!--link to some another page for testing-->
</body>
</html>
anotherpage.php
<?php
session_start();
echo "This is some another page somewhere inside.ANOTHER PAGE SAYS";
echo '<pre>';
print_r($_SESSION['POSTDATA']);
echo '<pre>';
echo "INPUT BOX VALUE ".$_SESSION['POSTDATA']['hello'].'<br/>';
echo "SUBMIT BUTTON VALUE ".$_SESSION['POSTDATA']['submit'];
?>
One possibility is to store the post data in $_session['post'] = $_POST to persist the storage and get the posted data on the new page with $_session['post']['field']
I can pass values form one page to another but I need to pass value like this,
Page 1:
Page4.php
Page3.php
I need to pass the value in a text field in the Page1.php to a text field in Page2.php, since the form is not directly redirectly to page2, I am unable to pass the value, I tried session, form post method and few other methods but I am yet to succeed.
I would be very happy if you can help me with the code or some suggestions.
Thanks!
Edit..........
I found the answer, thanks for the help, it was actually a careless mistake on my part, I used $_post instead of $_session.
Its working now.
Thanks for the help.
Use something like this:
page1.php
<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
Go to page2
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
I think that this problem occurs often on a web application development. But I'll try to explain in details my problem.
I'd like to know how to correct this behavior, for example, when I have a block of code like this :
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
die();
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
When the form gets submitted, the data get inserted into the database, and the message Operation Done is produced. Then, if I refreshed the page, the data would get inserted into the database again.
How this problem can be avoided? Any suggestion will be appreciated :)
Don't show the response after your create action; redirect to another page after the action completes instead. If someone refreshes, they're refreshing the GET requested page you redirected to.
// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Set a random number in a session when the form is displayed, and also put that number in a hidden field. If the posted number and the session number match, delete the session, run the query; if they don't, redisplay the form, and generate a new session number. This is the basic idea of XSRF tokens, you can read more about them, and their uses for security here: http://en.wikipedia.org/wiki/Cross-site_request_forgery
Here is an example:
<?php
session_start();
if (isset($_POST['formid']) && isset($_SESSION['formid']) && $_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
echo 'Process form';
}
else
{
$_SESSION["formid"] = md5(rand(0,10000000));
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="formid" value="<?php echo htmlspecialchars($_SESSION["formid"]); ?>" />
<input type="submit" name="submit" />
</form>
<?php } ?>
I ran into a similar problem. I need to show the user the result of the POST. I don't want to use sessions and I don't want to redirect with the result in the URL (it's kinda secure, I don't want it accidentally bookmarked). I found a pretty simple solution that should work for the cases mentioned in other answers.
On successfully submitting the form, include this bit of Javascript on the page:
<script>history.pushState({}, "", "")</script>
It pushes the current URL onto the history stack. Since this is a new item in history, refreshing won't re-POST.
UPDATE: This doesn't work in Safari. It's a known bug. But since it was originally reported in 2017, it may not be fixed soon. I've tried a few things (replaceState, etc), but haven't found a workaround in Safari. Here are some pertinent links regarding the issue:
Safari send POST request when refresh after pushState/replaceState
https://bugs.webkit.org/show_bug.cgi?id=202963
https://github.com/aurelia/history-browser/issues/34
Like this:
<?php
if(isset($_POST['uniqid']) AND $_POST['uniqid'] == $_SESSION['uniqid']){
// can't submit again
}
else{
// submit!
$_SESSION['uniqid'] = $_POST['uniqid'];
}
?>
<form action="page.php" method="post" name="myForm">
<input type="hidden" name="uniqid" value="<?php echo uniqid();?>" />
<!-- the rest of the fields here -->
</form>
I think it is simpler,
page.php
<?php
session_start();
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
$_SESSION["message"]="Operation Done";
header("Location:page.php");
exit;
}
?>
<html>
<body>
<div style='some styles'>
<?php
//message here
echo $_SESSION["message"];
?>
</div>
<form action='page.php' method='post'>
<!--elements-->
</form>
</body>
</html>
So, for what I needed this is what works.
Based on all of the above solutions this allows me to go from a form to another form, and to the n^ form , all the while preventing the same exact data from being "saved" over and over when a page is refreshed (and the post data from before lingers onto the new page).
Thanks to those who posted their solution which quickly led me to my own.
<?php
//Check if there was a post
if ($_POST) {
//Assuming there was a post, was it identical as the last time?
if (isset($_SESSION['pastData']) AND $_SESSION['pastData'] != $_POST) {
//No, Save
} else {
//Yes, Don't save
}
} else {
//Save
}
//Set the session to the most current post.
$_session['pastData'] = $_POST;
?>
We work on web apps where we design number of php forms. It is heck to write another page to get the data and submit it for each and every form. To avoid re-submission, in every table we created a 'random_check' field which is marked as 'Unique'.
On page loading generate a random value and store it in a text field (which is obviously hidden).
On SUBMIT save this random text value in 'random_check' field in your table. In case of re-submission query will through error because it can't insert the duplicate value.
After that you can display the error like
if ( !$result ) {
die( '<script>alertify.alert("Error while saving data OR you are resubmitting the form.");</script>' );
}
No need to redirect...
replace die(); with
isset(! $_POST['name']);
, setting the isset to isset not equal to $_POST['name'], so when you refresh it, it would not add anymore to your database, unless you click the submit button again.
<?
if (isset($_POST['name'])) {
... operation on database, like to insert $_POST['name'] in a table ...
echo "Operation Done";
isset(! $_POST['name']);
}
?>
<form action='page.php' method='post' name="myForm">
<input type="text" maxlength="50" name="name" class="input400" />
<input type="submit" name="Submit" />
</form>
This happen because of simply on refresh it will submit your request again.
So the idea to solve this issue by cure its root of cause.
I mean we can set up one session variable inside the form and check it when update.
if($_SESSION["csrf_token"] == $_POST['csrf_token'] )
{
// submit data
}
//inside from
$_SESSION["csrf_token"] = md5(rand(0,10000000)).time();
<input type="hidden" name="csrf_token" value="
htmlspecialchars($_SESSION["csrf_token"]);">
I think following is the better way to avoid resubmit or refresh the page.
$sample = $_POST['submit'];
if ($sample == "true")
{
//do it your code here
$sample = "false";
}