Pass post variables to next page [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So i basically have a form in html that submits to a preview page, where I access the variables to fill out the information on the page and display a preview of what the post will look like. I now want the user to be able to click a submit button and pass the same info to a new .php page that will handle submitting to database. I'm sure this is probably really easy, forgive me newbishness.
I have a form that submits to something like this and want is so when they click the "all good" button it sends the POST data on to a new .php page that can submit to the database and display a thank you message:
<?php
if (isset($_POST["preview"])) {
//get data
$firstvar = mysqli_real_escape_string($link, $_POST['name']);
$nextvar = mysqli_real_escape_string($link, $_POST['name']);
//etc
?>
<html>
//use vars in here
<p><a onclick="goBack()" class="btn btn-block btn-warning">Dont like what you see? Go back and fix it.</a></p>
<p>All good!</p>
</html>

JiteshNK provided one way of doing it using sessions.
Me, personally, I don't like to waste session variables on trivial things.
So another way you can do this is when you submit to your preview page (let's call preview.php), store the values in hidden input fields.
preview.php
<?php
if (isset($_POST["preview"])) {
// get data
$var1 = mysqli_real_escape_string($link, $_POST['var1']);
$var2 = mysqli_real_escape_string($link, $_POST['var2']);
// etc
?>
<!-- show vars -->
<form action="insert-page.php">
<!-- store vars into hidden input fields -->
<input type="hidden" name="var1" value="<?= $var1 ?>">
<input type="hidden" name="var2" value="<?= $var2 ?>">
<!-- etc -->
<p><a onclick="goBack()" class="btn btn-block btn-warning">Dont like what you see? Go back and fix it.</a></p>
<p><input type="submit" name="good" class="btn btn-block btn-success">All good!</a></p><!-- use submit button instead -->
</form>

Here is the below code.
<?php
include('connect.php');//connect.php is the connection file.
if(isset($_POST['submit']))//Here submit is the name of the form in HTML page.
{
$user_id=$_POST['user_id'];
$username=$_POST['username'];
$email=$_POST['email'];
$query = mysqli_query($con, "INSERT INTO sample (user_id, username, email)VALUES ('$user_id', '$username', '$email')");
header('Location: activation.php');
}
else
{
echo "<b>Error</b>";
}
mysqli_close($con);
?>

Related

How to achieve that the form will NOT resubmit and change the toggle status [duplicate]

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";
}

Login Screen - Not working

I've got a login screen all setup but my php code doesn't seem to work with it. Can't find the issue either as the details I'm entering are correct but it is not displaying either of the outputs. 1 - being proceed to next page. 2 - being display message saying incorrect details. Atleast thats what I think it should be doing. My code is here;
<?php
session_start();
if (isset($_POST['login'])):
require_once('my_connect.php');
$username=$_POST['username'];
$password=$_POST['password'];
$my_query="SELECT * from loanusers where username='$username' AND password='$password'";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) >0):
while ($myrow = mysqli_fetch_array($result)):
$_SESSION['userid'] = $myrow["userid"];
$_SESSION['username'] = $myrow["username"];
$_SESSION['password'] = $password;
$_SESSION['usertype'] = $myrow["usertype"];
$_SESSION['authenticated'] = true;
echo "<b> Hi ".$_SESSION['username']." (ID: ".$_SESSION['userid']."), You are now logged in!</b>";
endwhile;
//header('Location: homepage.php');
else:
echo "<b>Username or Password incorrect</b>";
endif;
mysqli_close();
endif;
require_once 'loginheader.php';
?>
<html>
<body>
<h2>User Login</h2>
<div id="loginp"><p>Need an Account? <a href='adduser.php'><b>Sign Up</b> </p></a></div>
<table>
<form method="POST" action="homepage.php" autocomplete="off">
<input type="text" name="username" placeholder="Username...">
<br><br>
<input type="password" name="password" placeholder="Password...">
<br><br>
<input type="submit" name="loanlogin" value="Sign In" onclick="window.location.href='homepage.php'">
</form>
</table>
<br>
<div id="loginp"><p>Forgot your Password?<b> Click Here</b></p></a></div>
<body>
<html>
Check these two Ideas:
What are the values of $usernameand $password before you issue them to the select statement. (i would guess they are empty, then remove the onclick)
is their really a username with this password in the database.
i would guess it's the onclick in your submit. You don't need this event their and it is not submitting the Form element.
Note that your code looks vulnerable to SQL and XSS injections, it's important to learn about security too while learning in PHP :-)
The html post action was taking me to another page bypassing the login script.
I changed the action to index.php and the login now displays an error if the details are incorrect and takes me to the take page if details are correct.
Thanks All for helping
Remove the onclick Like user nv1t said as, there is already an form action referring to the same page. onclick functions are only for <button> tags
To pull the value, check this how to get a selected database value as a session variable in php - stackoverflow
Click the tick near the answer if this helped.

Echo form data without sending to server

I have a tiny form on a page where I ask for the users name, the form sends the data to name.php and echos back the users name for example "Hello Steven" Steven being the name entered into the form.
Now that the name has been echoed to that form, I would like to echo that same data again elsewhere on the page. This is where I've run into a wall.
I would rather not send the names entered into the form to a server or database, but simply keep them for a session and then lose them.
The issue now is echoing the form data multiple times on one page.
The code I am using right now for the tiny form is as follows:
<form role="form" id="inviteform3" class="form-inline" action="name.php" method="POST">
<div class="form-group">
<input type="text" class="form-control input-sm" name="name" placeholder="Your Name"
id="hello" autocomplete="off" style="margin-top:10px">
</div>
<center>
<span id="result"></span>
<button class="btn btn-brand btn-sm next-screen animated bounceInUp"
id="go" style="margin-top:5px; display:none" href="#services" data-animation-delay=".5s">
Let's Go!</button></center>
<button class="btn btn-block btn-brand btn-xs invitebtn3" id="casi" type="submit"
style="margin-top:5px"><i class="fa fa-thumbs-o-up"></i> Submit</button>
</form>
My php form (name.php) is as follows:
<html>
<body>
Let's get started, <?php echo $_POST["name"]; ?>
</body>
</html>
and my js code is:
<script>
$(document).on("ready", function(){
//Form action
$("#inviteform3").on("submit", function(event){
// Stop submit event
event.preventDefault();
$.ajax({
type:'POST',
url: 'name.php',
data:$('#inviteform3').serialize(),
success: function(response)
{
$('#inviteform3').find('#result').html(response);
}});
});
});
</script>
We need to get a few things straight:
I would rather not send the names entered into the form to a server or database, but simply keep them for a session and then lose them.
You ARE sending that data to the server, you have used jQuery and AJAX to POST your form to name.php (php works on the server) from which you receive the response and add it your page with the line:
$('#inviteform3').find('#result').html(response);
If you want to KEEP that data stored (for example in a session), you can use the PHP suggested by Antony D'Andrea in name.php. When the browser is closed, the session is destroyed. Untill then you can use the session variable where ever you want.
Now that the name has been echoed to that form, I would like to echo
that same data again elsewhere on the page. This is where I've run
into a wall.
You are echoing the name in name.php, your AJAX call then retrieves the whole page (including the html and body tags) and adds it to #result. If you want to show the name mulitple times, just append it multiple times with the line above.
$("#inviteform3").on("submit", function(event) {
var name = $("form input['name']").val();
// Here is the interesting part
sessionStorage.setItem("name", name);
}
// Get that name
var access_name = sessionStorage.getItem("name");
$("#some_id").html(access_name); // Inserts the name where you want it.
sessionStorage is wiped every time the tab/window is closed.
You could use PHP instead of Javascript.
session_start();
$_SESSION['name'] = $_POST['name'];
The $_SESSION variable is cleared when the browser is closed and is global so can be accessed anywhere. session_start has to be the very first thing you do though on line 1 of the first page that is run.
More info about sessions in PHP can be found here and the about $_SESSION here.
For example:
You are posting to name.php. So on line 1 of name.php do
<?php session_start(); ?>
Then do
<?php
if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
}
?>
Then wherever you want to use it, just do echo $_SESSION['name'];
If you want to echo in other files. Then in line 1 of the other file do
<?php session_start(); ?>
Then:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
}
?>
The if statement is just there for checking, but you don't need it if you are confident it is set.

How to store session in php? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have create session in header.php but when I change my page session get destroyed automatically .
session start this code i have place at very top of header.php
session_start();
php code for session
<?php $_SESSION['lang'] = $_GET['herbew'];
if(isset($_SESSION['lang'])){
echo $_SESSION['lang']; } ?>
HTML where I give option to user to change language
<form action="<?php echo $_SERVER['REQUEST_URI']?>" method="get">
<div class="lang">
<span class="english"><input type="hidden" name="english" value="english">
<input type="submit" name="submitsd" value="eng" ></span>
<span class="herbew"><input type="hidden" name="herbew" value="herbew">
<input type="submit" name="submit" value="her" ></span>
</div>
</form>
A session must be started inorder to access the session variables.
At the top of the page add:
session_start();
This will start a session. it's also required to have session_start(); on every page that uses the session array.
If you are looking to add data to the session array. You will need to do this after user presses the submit button. Ie,
Form > Redirects to AddSess.php > Adds required values to session > Redirects to the correct page
Ie:
<form action="AddSess.php" method="POST">
<input type="text" name="test">
<input type="submit" name="submit">
</form>
and on AddSess.php
session_start();
if (isset($_POST['submit'])){
$_SESSION[] = $_POST['test'];
header ("Location: index.php");
}
The above is a very basic example on how to append data to a session
Add variable in session variable in PHP
You are overwriting your session variable everytime the page is called. if $_GET['herbew'] is empty, so will be $_SESSION['lang']
Check $_GET before you assign it:
if (isset($_GET['herbew'])) {
$_SESSION['lang'] = $_GET['herbew'];
}
if(isset($_SESSION['lang'])) {
echo $_SESSION['lang'];
}

Best way to avoid the submit due to a refresh of the page

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";
}

Categories