Hello i have my form and i want to implement this method for preventing double submitting on forms or going back
The simple code:
<?php
// start session
session_start();
// create unique token
$form_token = uniqid();
// commit token to session
$_SESSION['user_token'] = $form_token;
?>
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Prevent multiple POSTs </title>
</head>
<body>
<form action="submit.php" method="post">
<input type="text" name="bar" />
<input type="hidden" name="user_token" value="<?php echo $_SESSION['user_token']; ?>" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
And here the submit.php code:
<?php
session_start();
//We check if the token of the page and session match!
if($_POST['user_token'] == $_SESSION['user_token']) {
$message = 'Your download is Here ';
} else {
$message = 'Your request has expired, please go back and resubmit!';
}
echo "We say: " . $message;
// invalidate the token so it expires on view, important!
unset($_SESSION['user_token']);
?>
I uploaded this script to my server but whenever i click the submit button i get the same answer the We say: Your download is Here echo , why this i checked if my cookies are created and yes they exists as they should ,
i want that users that have submitted the form once , to cant do that another time until a refresh or setting a maximum time that these cookies can exists and than delete them so that the user after for eg 10 min can submit another form if he want so
Any help will greatly be welcomed. Thanks in advance. Updatet
session_start();
Add this in the begining of second script which recive your data from form.
More detailes in manual.
But the only way to recieve msg 'Your request has expired' you need to keep recieved data in some form on server (file or data base) I suppose.
Related
I've spent a lot of time today researching this site for my solution but I have had no luck. I'm currently trying to learn php and working on my second project. I can only use PHP. I originally had my delete session and redirect in a separate logout.php file. This was working but then I found out that I can't do this. I've been instructed that I need to "clear the login, delete the session, and redirect back to the login page" and do this within an isPostBack in the results.php file. After a lot of research today I thought I was understanding how to do this but I can't get it to work. Hoping I can get some help.
<?php
session_start();
//require_once('cookies.php');
$isPostBack = filter_input(INPUT_GET, 'submit');
//this is where I need to do the isPostBack for user clicking "logout".
if ($isPostBack) {
// clear ALL session data from memory
// clean up the session and remove the session ID.
// redirect to index.php
endSession();
session_destroy();
header("Location: index.php");
} else {
// user did not click logout doNothing();
}
?>
<html lang="en">
<head>
<title>Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="results.php">
<input type="submit" id="submit" name="submit" value="Logout" />
</form>
<section>
<?php
foreach($_SESSION['answers'] as $answer){
echo "<p>$answer</p>";
}
?>
</section>
</body>
Try to provide name attribute
<input type="submit" id="submit" value="Logout" name="logout"/>
and use only logout variable in place of submit or provide two different fields
$isPostBack = filter_input(INPUT_GET, 'submit');
$isPostBack = filter_input(INPUT_GET, 'logout');
I seem to have found my solution. I needed to give the isPostBack variable a name that matched the name given to the logout button. I also needed to include !==NULL after the isPostBack. I changed endSession(); to $_SESSION = array(); According to my research, endSession(); "removes all session variables". It seems to be working as it should now. Here is my edited code.
<?php
session_start();
$isPostBack = filter_input(INPUT_GET, 'submit')!==NUll;
//this is where I need to do the isPostBack for user clicking "logout".
if ($isPostBack) {
// clear ALL session data from memory
// clean up the session and remove the session ID.
// redirect to index.php
$_SESSION = array();
session_destroy();
header("Location: index.php");
} else {
// user did not click logout doNothing();
}
?>
<html lang="en">
<head>
<title>Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="results.php">
<input type="submit" id="submit" name="submit" value="Logout" />
</form>
<section>
<?php
foreach($_SESSION['answers'] as $answer){
echo "<p> $answer</p>";
}
?>
</section>
</body>
If you need to remove se particular session values you can use unset()
unset ($_SESSION['userid'])
I have the following problem and feel that the solution is simple but after 8 hours of trying and searching, I am giving up.
I have this simple page:
<?php
// Start the session
$lifetime=600;
session_set_cookie_params($lifetime);
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Change the Yoda!</title>
</head>
<body>
<?php
// Set session variables
$_SESSION["post-data"] = $_POST;
?>
<form action="yoda_is.php" method="POST">
YODA IS: <input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
Upon submit, it sends me to this page:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Who is Yoda?</title>
</head>
<body>
<?php
// Echo session variables that were set on previous page
echo "YODA IS " . $_SESSION['post-data'] = $_POST['name'];
?>!
</body>
</html>
The value that you enter in the first page, is successfully being displayed on the second page.
However, once I close the browser window and revisit the second page, the value is no longer there and it returns an error.
My question is simple, what am I doing wrong / do I need to do in order for the value that I entered on the first page, to be there after I revisit the second page?
Thank you so much for your help and suggestions, in advanced.
KR
MD
On your first page remove this:
// Set session variables
$_SESSION["post-data"] = $_POST;
On your second page use this instead:
// If the user filled out the form, set our session variable to the new value
if(isset($_POST['name']))
{
$_SESSION['post-data'] = $_POST['name'];
}
// Echo session variable set above
echo "YODA IS " . $_SESSION['post-data'] . "!";
I'm trying to make a password only login in php, because I have a "pocket server" wich always changes domains (I use ngrok so I don't have to portforward), And I need a domain tracer so my users always know the link to my pocket server, I already have a website and I want to make it so I don't have to make a complicated login system, I want to identify myself just by a password and nothing else, the website is simple it has a textbox and some text
Goals:
-Have a simple password login
-And If I am logged in, i can change the domain displayed on the public website
My code so far:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Killer Doge</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Killer Doge Tracer (Link changes daily)</h1>
<?php
$text = "domain";
?>
<p>Current domain:</p>
<?php
echo $text;
?>
<br>
<?php echo '<input type="text" name="name1" value="'.$admin.'">';
If ($admin == "694205") {
echo yees;
}
?>
</body>
</html>
It's pretty much what #Maarten van Middelaar said, but a tad more complicated.
I'll try to explain through code comments:
<?php // always start the session first.
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
//Check if loginform was submitted:
if(isset($_POST['admin'])){
if($_POST['admin'] == '12345678'){
//user logged in correctly, store in session so you don't get instantly logged out:
$_SESSION['loggedIn'] = "logged in!";
}
}
//check if domainchanger form was submitted and user is logged in
if(isset($_POST['newdomain']) && isset($_SESSION['loggedIn'])){
$newDomain = $_POST['newdomain'];
//TODO: Set new domain in the database so your website can retrieve it.
}
//Check if user is not logged in already
if(!isset($_SESSION['loggedIn'])):
//Show login form if not logged in
?>
<form method="post">
<input type='text' name='admin' />
<input type='submit' value="log in!" />
</form>
<?php else:
//if logged in, show domain changer thing
//Show the current domain as the default value for the input
//TODO: make database connection here to get current domain
//structure: Create query to get current domain -> $currentDomain = dbresult
?>
<form method="post">
<input type="text" name="newdomain" value="<?= $currentDomain ?>" />
<input type='submit' value="change domain!"/>
</form>
<?php endif ?>
I hope this makes everything clear. Tried to do it as step-by-step as possible.
Please let me know if you have any questions :)
Suppose, I have two pages: page01.php and page02.php (their code is presented below).
If I leave action attribute in the form on page01.php empty (i.e. action=""), then access page01.php, fill in the form, press submit, then access page02.php - it all works fine (i.e. $_SESSION variable stores the data submitted on page01.php and can be accessed and viewed on page02.php as expected).
However, when I try to make the form send the user to page02.php (by changing the action atrribute to action="page02.php") it looks like the $_SESSION global variable doesn't store data from page01.php.
My question is: does this happen because the user is redirected to page02.php immediately upon submission of form and the code between php tags on page01.php does not get executed?
I'm aware I can use $_GET or $_POST on page02.php to achieve the desired behavior, but I'm just trying to understand the way action attribute and $_SESSION interact. Thank you.
Page01.php:
<html>
<head>
<title>Page 01</title>
</head>
<body>
<h1>Please fill this form</h1>
<form action="" method="post">
Name: <input name="username">
<input type="submit" value="send">
</form>
<?php
session_start();
if(isset($_POST['username'])) {
$_SESSION['username']=$_POST['username'];
}
?>
</body>
Page02.php:
<html>
<head>
<title>Page 02</title>
</head>
<body>
<h1>Another temporary page is working</h1>
<?php
session_start();
$expectedName = "Bob";
if($_SESSION['username'] == $expectedName) {
echo "Welcome, Bob!";
}
else {
echo "Access denied. You are ". $_SESSION['username'] . ", not Bob.";
}
?>
</body>
action attribute is attribute you specify where the script that will need to be run after submitting.
so if you want user to be redirected after form has been submitted, you use header() function.
I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)