PHP form with multiple steps and validation - php

I'm new to PHP and I'm trying to create an easy form that has multiple steps. For each step, a validation of the input is happening before the user is directed to the next page. If the validation fails, the user should stay on the same page and an error message should be displayed. In the end, all entries that the user has made should be displayed in an overview page.
What I have been doing to solve this, is to use a boolean for each page and only once this is true, the user can go to the next page. This is not working as expected unfortunately and I guess it has something to do with sessions in PHP... I also guess that there's a nicer way to do this. I would appreciate some help!
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
session_start();
$_SESSION['$entryOne'] = "";
$_SESSION['$entryOneErr'] = $_SESSION['$emptyFieldErr'] = "";
$_SESSION['entryOneIsValid'] = false;
$_SESSION['$entryTwo'] = "";
$_SESSION['$entryTwoErr'] = "";
$_SESSION['entryTwoIsValid'] = false;
// Validation for first page
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryOne'])) {
if (!empty($_POST["entryOne"])) {
// Check for special characters
$_SESSION['$entryOne'] = removeWhitespaces($_POST["entryOne"]);
$_SESSION['$entryOneErr'] = testForIllegalCharError($_SESSION['$entryOne'], $_SESSION['$entryOneErr']);
// If error text is empty set first page to valid
if(empty($_SESSION['$entryOneErr'])){
$_SESSION['$entryOneIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
// Validation for second page
} else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submitEntryTwo'])) {
if (!empty($_POST["entryTwo"])) {
// Check for special characters
$_SESSION['$entryTwo'] = removeWhitespaces($_POST["entryTwo"]);
$_SESSION['$entryTwoErr'] = testForIllegalCharError($_SESSION['$entryTwo'], $_SESSION['$entryTwoErr']);
// If error text is empty set second page to valid
if(empty($_SESSION['$entryTwoErr'])){
$_SESSION['$entryTwoIsValid'] = true;
}
} else {
// Show error if field hasn't been filled
$_SESSION['$emptyFieldErr'] = "Please enter something!";
}
}
//Remove whitespaces at beginning and end of an entry
function removeWhitespaces($data) {
$data = trim($data);
return $data;
}
//Check that no special characters were entered. If so, set error
function testForIllegalCharError($wish, $error){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar,$wish)) {
$error = "Special characters are not allowed";
} else {
$error = "";
}
return $error;
}
?>
<?php if (isset($_POST['submitEntryOne']) && $_SESSION['$entryOneIsValid'] && !$_SESSION['$entryTwoIsValid']): ?>
<h2>Second page</h2>
<p>Entry from first Page: <?php echo $_SESSION['$entryOne'];?></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Entry Two: <input type="text" name="entryTwo" value="<?php echo $_SESSION['$entryTwo'];?>">
<span class="error"><?php echo $_SESSION['$entryTwoErr'];?></span>
<br><br>
<input type="submit" name="submitEntryTwo" value="Next">
</form>
<?php elseif (isset($_POST['submitEntryTwo']) && $_SESSION['$entryTwoIsValid']): ?>
<h2>Overview</h2>
<p>First entry: <?php echo $_SESSION['$entryOne'];?></p>
<p>Second Entry: <?php echo $_SESSION['$entryTwo'];?></p>
<?php else: ?>
<h2>First page</h2>
<span class="error"><?php echo $_SESSION['$emptyFieldErr'];?></span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br><br>
First entry: <input type="text" name="entryOne" value="<?php echo $_SESSION['$entryOne'];?>">
<span class="error"> <?php echo $_SESSION['$entryOneErr'];?></span>
<br><br>
<input type="submit" name="submitEntryOne" value="Next">
</form>
<?php endif; ?>
</body>
</html>

You are setting your session variables to "" at the top of your script.
Check if your variable is set before setting to blank.
Check if Session Variable is Set First
<?php
//If variable is set, use it. Otherwise, set to null.
// This will carry the variable session to session.
$entryOne = isset($_REQUEST['entryOne']) ? $_REQUEST['entryOne'] : null;
if($entryOne) {
doSomething();
}
?>
Tips
Then you can use <?= notation to also echo the variable.
Do this $_SESSION['variable'] instead of $_SESSION['$variable'] (you'll spare yourself some variable mistakes).
<h2>Second page</h2>
<p>Entry from first Page: <?= $entryOne ?></p>
Example Script
This could be dramatically improved, but for a quick pass:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Check that no special characters were entered. If so, set error
function hasIllegalChar($input){
$illegalChar = '/[\'\/~`\!##\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
if (preg_match($illegalChar, $input)) {
return true;
}
return false;
}
session_start();
// Destroy session and redirect if reset form link is pressed.
if(isset($_GET['resetForm']) && $_GET['resetForm'] == "yes")
{
echo "SESSION DESTROY";
session_destroy();
header("Location: ?");
}
// Session
$page = isset($_SESSION['page']) ? $_SESSION['page'] : 1;
$errors = [];
// Value history.
$valueOne = isset($_SESSION['valueOne']) ? $_SESSION['valueOne'] : null;
$valueTwo = isset($_SESSION['valueTwo']) ? $_SESSION['valueTwo'] : null;
// Clean inputs here
$fieldOne = isset($_REQUEST['fieldOne']) ? trim($_REQUEST['fieldOne']) : null;
$fieldTwo = isset($_REQUEST['fieldTwo']) ? trim($_REQUEST['fieldTwo']) : null;
// First form
if ($page == 1) {
// If field two is submitted:
if ($fieldOne) {
//Validate inputs
if(hasIllegalChar($fieldOne)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueOne = $_SESSION['valueOne'] = $fieldOne;
$page = $_SESSION['page'] = 2;
}
}
}
// Second form
else if ($page == 2) {
// If field two is submitted:
if ($fieldTwo) {
//Validate inputs
if(hasIllegalChar($fieldTwo)) {
$errors[] = "You entered an invalid character.";
}
if (count($errors) == 0 ){
$valueTwo = $_SESSION['valueTwo'] = $fieldTwo;
$page = $_SESSION['page'] = 3;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Test</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<?php
// troubleshoot
if (true) {
echo "<pre>";
var_dump($_REQUEST);
var_dump($_SESSION);
echo "</pre>";
}
echo "<h1>Page " . $page . '</h1>';
if (count($errors) > 0) {
$errorMsg = implode('<br/>',$errors);
echo '<div class="error">Some errors occurred:<br/>' . $errorMsg . '</div>';
}
?>
<?php if ($page == 3): ?>
<h2>Overview</h2>
<p>First entry: <?= $valueOne;?></p>
<p>Second Entry: <?= $valueTwo;?></p>
Reset
<?php elseif ($page == 2): ?>
<p>Entry from first Page: <?= $valueOne; ?></p>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
Entry Two: <input type="text" name="fieldTwo" value="<?= $fieldTwo ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php else: ?>
<form method="post" action="<?= $_SERVER["PHP_SELF"] ?>">
<br><br>
Entry One: <input type="text" name="fieldOne" value="<?= $fieldOne; ?>" autofocus>
<br><br>
<input type="submit">
</form>
<?php endif; ?>
</body>
<html>
You can run the following command to test out the page without using a fancy tool like WAMP or LAMP.
php -S localhost:8000 index.php
You can now access in the browser at http://localhost:8000.

Related

How Can i use includ in php without excute the first page code

i try to get a variable from header page to a game page.. but when i do it with include 'header.php" he excute the header code in game.php ( header("refresh"))
i wanna to excute the refresh one time in first page only
header.php code :
<?php
$memory = "ahmed";
echo "Remember This Word : " . $memory;
header("Refresh: 5; url= game.php");
// exit;
?>
game.php code :
<?php
// ob_start();
// include "header.php";
// ob_end_clean();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if($_POST['solution'] == "ahmed") {
$_SESSION['username'] = $_POST['solution'];
} else {
echo "Try again";
}
}
if(isset($_SESSION['username'])) {
echo "Well Done <br>";
echo ' Play again';
} else {
?>
<form action="" method="POST">
<input type="text" name="solution" id="">
<input type="submit" value="check">
</form>
<?php } ?>

php script using sessions formatting and redirecting to 500

I am new to php and working on a hangman game. I have a home.php that takes you to the homepage and their is a login form that the user must submit a username and a password. If the username and password match with the one I have set, it will redirect to hangman.php. I want some advice if the way I have written the script is correct or not. Also, I am getting a 500 error after the user logs in. I don't know why. I will paste the code down below.
Update: I have added the code for hangman.php
home.php
<?php
// starting a new session
session_start();
if(isset($_POST['uname'], $_POST['psw'])){
$uname= "my_admin";
$psw = "password";
if($_POST['uname'] == $uname && $_POST['psw'] == $psw) {
$_SESSION["uname"] = "my_admin";
$_SESSION["psw"] = "password";
# array holds errors
$errors = array();
# validation starts here
if(empty($_POST['uname'])){
$errors['uname1'] = "Your name cannot be empty";
}
# check strlength
if(strlen($_POST['uname']) < 6){
$errors['uname2'] = "Must be longer than 6 characters";
}
# check username
if ($_POST['uname'] !== "my_admin"){
$errors['uname3'] = "You are not the admin";
}
if($_POST['uname'] == "my_admin" && $_POST['psw'] == "password"){
header('Location:hangman.php');
exit();
}else{
$errors['uname4'] = "Please try again";
}
if(empty($_POST['psw'])){
$errors['psw1'] = "Your password cannot be empty";
}
if(strlen($_POST['psw']) < 6){
$errors['psw2'] = "Must be longer than 6 characters";
}
if($_POST['psw'] !== "password"){
$errors['ps3'] = "AH AH AH thats not it";
}else{
header('Location:hangman.php');
exit();
}
if(count($errors) == 0){
# redirect to the game page
header('Location:hangman.php');
exit();
}
}
}
?>
form for my script to run against
<div class="container">
</p>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname">
<p>
<?php if(isset($errors['uname1']))
echo $errors['uname1']; ?>
</p>
<p>
<?php if(isset($errors['uname2']))
echo $errors['uname2']; ?>
</p>
<p>
<?php if(isset($errors['uname3']))
echo $errors['uname3']; ?>
</p>
<p>
<?php if(isset($errors['uname4']))
echo $errors['uname4']; ?>
</p>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw">
<p>
<?php if(isset($errors['psw1'])) echo $errors['psw1']; ?>
</p>
<p>
<?php if(isset($errors['psw2'])) echo $errors['psw2']; ?>
</p>
<?php if(isset($errors['psw3'])) echo $errors['psw3']; ?>
</p>
<button name="check" type="submit" value="submit">Login</button>
</div>
</form>
hangman.php
<?php
require_once 'hangedman.php';
$words = array('VIETNAM', 'PEOPLE', 'PYTHON');
$numwords = 0;
function printPage($image, $guesstemplate, $which, $guessed, $wrong) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
<link rel="stylesheet" type="text/css" href="home.css">
</head>
</html>
<body>
<h1 style='color: red'>Hangman Game</h1>
<br />
<pre style='color: red'>$image</pre>
<br />
<p style='color:red'><strong>Word to guess: $guesstemplate</strong></p>
<p style='color:red'>Letters used in guesses so far: $guessed</p>
<form method="post" action="$script">
<input type="hidden" name="wrong" value="$wrong" />
<input type="hidden" name="lettersguessed" value="$guessed" />
<input type="hidden" name="word" value="$which" />
<fieldset>
<legend style='color: red'>Your next guess</legend>
<input type="text" name="letter" autofocus />
<input type="submit" value="Guess" />
</fieldset>
</form>
</body>
ENDPAGE;
}
function loadWords() {
global $words;
global $numwords;
$input = fopen("./words.txt", "r");
while (true) {
$str = fgets($input);
if (!$str) break;
$words[] = rtrim($str);
$numwords++;
}
fclose($input);
}
function startGame() {
global $words;
global $numwords;
global $hang;
$which = rand(0, $numwords - 1);
$word = $words[$which];
$len = strlen($word);
$guesstemplate = str_repeat('_ ', $len);
$script = $_SERVER["PHP_SELF"];
printPage($hang[0], $guesstemplate, $which, "", 0);
}
function killPlayer($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You lost!</h1>
<p>The word you were trying to guess was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function congratulateWinner($word) {
echo <<<ENDPAGE
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>You win!</h1>
<p>Congratulations! You guessed that the word was <em>$word</em>.</p>
</body>
</html>
ENDPAGE;
}
function matchLetters($word, $guessedLetters) {
$len = strlen($word);
$guesstemplate = str_repeat("_ ", $len);
for ($i = 0; $i < $len; $i++) {
$ch = $word[$i];
if (strstr($guessedLetters, $ch)) {
$pos = 2 * $i;
$guesstemplate[$pos] = $ch;
}
}
return $guesstemplate;
}
function handleGuess() {
global $words;
global $hang;
$which = $_POST["word"];
$word = $words[$which];
$wrong = $_POST["wrong"];
$lettersguessed = $_POST["lettersguessed"];
$guess = $_POST["letter"];
$letter = strtoupper($guess[0]);
if(!strstr($word, $letter)) {
$wrong++;
}
$lettersguessed = $lettersguessed . $letter;
$guesstemplate = matchLetters($word, $lettersguessed);
if (!strstr($guesstemplate, "_")) {
congratulateWinner($word);
} else if ($wrong >= 6) {
killPlayer($word);
} else {
printPage($hang[$wrong], $guesstemplate, $which, $lettersguessed, $wrong);
}
}
//header("Content-type: text/plain");
loadWords();
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
handleGuess();
} else {
startGame();
}
?>

(PHP) Adding a 'guess counter' to a random number game

I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.
I was wondering how it would be properly implemented into my code.
This is what I have so far.
<?php
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$count++; //Declare the variable $count to increment by 1.
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
You have to use PHP Sessions to keep track of the count.
All you have to do is initialize counter to 0 and have it increment when the user guesses a number
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["count"] = 0; //Initialize count
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else { // must be equivalent
$_SESSION["count"]++;
$message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!";
unset($_SESSION["count"]);
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
This should work for you.
$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<input type="hidden" name="count"
value="<?php echo $count; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
that's all folks ...

How do I submit a form's data automatically after successful PHP validation?

This is what I did in a nutshell:
<?php
// define variables and initialize with empty values
//error variables
$agentNameErr = "";
//non-error variables
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
}
else {
$agentname = $_POST["agentname"];
}
}
// form
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<span class="error"><?php echo $agentNameErr;?></span>
</form>
It checks if $agentname is erroneous (blank). If it's not blank, I don't know how to proceed. I want it to just automatically submit all the information without any additional user input to a review page so the user can see if the name was spelled correctly. And then they can do a final submission.
I don't know MySQL.
In normal english:
//user presses the submit button
if ($agentname has error)
stay on page and display errors
else
submit automatically to next page (order review page for visual checking)
What do I do to "submit automatically to next page"?
Use a php session.
if ($agentname has error)
stay on page and display errors
else
{
$_SESSION['key1'] = 'something'
$_SESSION['key2'] = 'something else'
...
header('location: ' . $next_page);
}
If you don't know how to use php sessions see the examples here
Try this:
<?php
$agentNameErr = "";
$agentemail = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["agentname"])) {
$agentNameErr = "Missing";
} else {
$agentname = $_POST["agentname"];
header("Location: nextpage.php?agent=".$agentname);
}
} else {
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<input name="agentname" type="text" id="agentname" autocomplete="on" placeholder="Agent Name" value= "<?php echo htmlspecialchars($agentname);?>" />
//only shows up if $agentNameErr is assigned the value of "Missing"
<?php if(!empty($agentNameErr)) { ?>
<span class="error"><?php echo $agentNameErr;?></span>
<?php } ?>
</form>
<?php } ?>
Keep it simple. Capture the entire contents of the form and store in a session variable.
$agentNameErr = '';
$agentemail = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['agentname'])) {
$agentNameErr = 'Missing';
} else {
$_SESSION['agent-form'] = $_POST;
// Move to next page
header('Location: nextpage.php');
exit;
}
}
Once forwarded to the next page you can access the form data from the session variable.
// Entire contents of form
print_r($_SESSION['agent-form']);
// "agentname" data
print_r($_SESSION['agent-form']['agentname']);

variables not posting php form

So I'm working on this password reset form. Where a user clicks on a link sent to their email and they are taken to a webpage to enter a new password. When they submit the form 3 variables (password, key, & email) are passed to my functions file to update the password for the user. The password itself is being posted, but the email and key are not. I did a vardump to see what is actually being sent and its just displaying the code in the values of email/key on the form. I'm not sure what I'm doing wrong.
EDIT
So I figured out that the email/key were not being passed to the updateUserPassword() function. I posted the new correct form code below. SOLVED
<?php session_start();
include("include/DB_Connect.php");
include("include/DB_Functions.php"); // Connect to database server(localhost) with username and password.
mysql_select_db("android_api") or die(mysql_error()); // Select registration database.
$show = 'emailForm'; //which form step to show by default
if (isset($_POST['subStep']) && !isset($_GET['a']))
{
switch($_POST['subStep'])
{
case 1:
//we are submitting a new password (only for encrypted)
if ($_POST['email'] == '' || $_POST['key'] == '') header("location: forgotpw.php");
if (strcmp($_POST['password'],$_POST['pw1']) != 0 || trim($_POST['password']) == '')
{
$error = true;
$show = 'recoverForm';
} else {
$error = false;
$show = 'recoverSuccess';
updateUserPassword($_POST['email'],$_POST['password'],$_POST['key']);
var_dump($_POST['email'],$_POST['password'],$_POST['key']);
}
break;
}
} elseif (isset($_GET['a']) && $_GET['a'] == 'recover' && $_GET['email'] != "") {
$show = 'invalidKey';
$result = checkEmailKey(urldecode(base64_decode($_GET['email'])),$_GET['key']);
if ($result == false)
{
$error = true;
$show = 'invalidKey';
} elseif ($result['status'] == true) {
$error = false;
$show = 'recoverForm';
$securityUser = $result['email'];
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Password Recovery</title>
<link href="assets/css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="header"></div>
<div id="page">
<?php switch($show) {
case 'recoverForm': ?>
<h2>Password Recovery</h2>
<p>Welcome back, <?php echo getUserName($securityUser=='' ? $_GET['email'] : $securityUser); ?>.</p>
<p>In the fields below, enter your new password.</p>
<?php if ($error == true) { ?><span class="error">The new passwords must match and must not be empty.</span><?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="fieldGroup"><label for="password">New Password</label><div class="field"><input type="password" class="input" name="password" id="password" value="" maxlength="20"></div></div>
<div class="fieldGroup"><label for="pw1">Confirm Password</label><div class="field"><input type="password" class="input" name="pw1" id="pw1" value="" maxlength="20"></div></div>
<input type="hidden" name="subStep" value="1" />
<input type="hidden" name="email" value="<?php echo $securityUser=='' ? $_POST['email'] : $securityUser; ?>" />
<input type="hidden" name="key" value="<?php echo $_GET['key']=='' ? $_POST['key'] : $_GET['key']; ?>" />
<div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
<div class="clear"></div>
</form>
<?php break; case 'invalidKey': ?>
<h2>Invalid Key</h2>
<p>The key that you entered was invalid. Either you did not copy the entire key from the email, you are trying to use the key after it has expired (3 days after request), or you have already used the key in which case it is deactivated.<br /><br />Return to the login page. </p>
<?php break; case 'recoverSuccess': ?>
<h2>Password Reset</h2>
<p>Congratulations! your password has been reset successfully.</p><br /><br />Return to the login page. </p>
<?php break; }
ob_flush();
$mySQL->close();
?>
</div>
</body>
</html>
Here is my function code:
function updateUserPassword($email,$password,$key)
{
global $mySQL;
if (checkEmailKey($email,$key) === false) return false;
if ($SQL = $mySQL->prepare("UPDATE `users` SET `encrypted_password` = ? WHERE `email` = ?"))
{
$password = md5(trim($password) . PW_SALT);
$SQL->bind_param('ss',$email,$password);
$SQL->execute();
$SQL->close();
$SQL = $mySQL->prepare("DELETE FROM `recoveryemails_enc` WHERE `Key` = ?");
$SQL->bind_param('s',$key);
$SQL->execute();
}
}

Categories