Keep text in text field after submit - php

I'm building a form, and I want that all the inserted values will be kept, in case of form submit failure. This is my code:
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value=""/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
I would like that name field keeps the inserted input text, after submit. I tried to do with php code in input value but doesn't work. Any ideas?

Solved. This is the solution that I was looking for.
I added in value tag of input the following:
<?php if (isset($_POST['name'])) echo $_POST['name']; ?>
Therefore input field would look like:
<input type="text" placeholder="Name" id="name" name="name" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"/>
Thanks for your responses, helped me.

<?php
$error = "";
$name = isset($_POST["name"])?$_POST["name"]:""; //Added condition
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>

You can just echo $_POST['name'] in the value attribute of the input.
Make sure you check POST values to avoid XSS.
I also put up the update DB function, as you don't need to show the form to the user if the name in longer the 4 chars!
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['name'])){ //change name content only if the post value is set!
$name = filter_input (INPUT_POST, 'name', FILTER_SANITIZE_STRING); //filter value
}
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
} else {
// Update name in DB
// Redirect
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
};
?>
</body>
</html>

If you want to keep all values/inputs for further use you could achieve that with php session values.
Besides - you should use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']
Mars

Related

I am getting a really weird result on my php form output

Here is my code:
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$age = $_POST['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_GET['getName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$age = $_GET['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
I have two forms. Both displaying the exact same thing, but one form using POST and one using GET.
I have gotten so close to finishing this off but now I have another small/weird issue.
The code technically works correctly, but here's the output explanation:
when I first open up the page the GET form already has the result "Sorry, try again when you're 16 or older." When I fill out the first 'simple' form, it displays the result correctly but then the POST form shows the "Sorry, try again..." result. Then, when I fill in the information and click submit, it displays the correct result and the other two forms are blank as they're supposed to be, and then the same result when I fill out the GET form.
Any help on this is much appreciated.
Try this code :
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
if (isset($_POST['firstName']) && $_POST['lastName'])
{
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
}
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_POST['postName']))
{
echo $_POST['postName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST['age']))
{
$age = $_POST['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_GET['getName']))
{
echo $_GET['getName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if (isset($_GET['age']))
{
$age = $_GET ['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
Please try this. I hope it will help.
Replace
if ($_SERVER['REQUEST_METHOD'] == "POST") {
with
if (isset($_POST['age'])) {
Similarly,Replace
if ($_SERVER['REQUEST_METHOD'] == "GET") {
with
if (isset($_GET['age'])) {
When you first enter on page, default REQUEST_METHOD is GET so you should check if isset($_GET['age']) {
and here check if it is more than 16
}
also you should check this one
echo $_GET['getName']; and change on this
echo isset($_GET['getName']) ? $_GET['name'] : "";
You should also check $_POST request like this and your program will work correctly.

PHP Sticky Forms

I've been doing a project for php, about sticky keys. It's quite straight forward. However I'm getting a few errors... I'm using CodeLobster.
Can anyone help me find my error on this ?
I've been looking for 2hrs now, I tried the debug, but I don't really know how to use it here.
Thank you so much. Any helps will be appreciated
This is what I am getting:
Output should be this:
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($_POST['phone'] == ""){
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" /><br/>
<?php echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $_POST['phone']; ?>" /><br/>
<?php echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
Can you please check once this code:-
<html><head><title>Empty Fields</title>
<body><div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
if(isset($_POST['submit'])){
validate_input();
if(count($errors) != 0){
display_form();
}
else{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else{
display_form();
}
function validate_input(){
global $errors;
if($_POST['name'] == ""){
$errors['name'] = "Your name?";
}
if($_POST['phone'] == ""){
$errors['phone'] = "Your phone?";
}
}
function display_form(){
global $errors;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php if(isset($_POST['name'])){echo $_POST['name'];} ?>" /><br/>
<?php if(isset($errors['name'])){echo $errors['name'];} ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php if(isset($_POST['name'])){$_POST['phone'];} ?>" /><br/>
<?php if(isset($errors['phone'])){echo $errors['phone'];} ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
I try to revise your code, There are many point to fixed.
First, you need to keep $_POST['name'] and $_POST['phone'] in variable for easy to use in each function.
Like this,
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
You also need to add code below to first line in function that need to use this variable
global $name;
global $phone;
In function display_form you need to check $errors['name'] and $errors['name'] is empty or not before print(echo) the line.
if (isset($errors['name'])) echo $errors['name'];
if (isset($errors['phone'])) echo $errors['phone'];
So, Finally the code should be like the below, I tried this code without error.
<html>
<head><title>Empty Fields</title>
<body>
<div align="center">
<h2>Validating Input</h2>
<?php
$errors = array();
$name = (isset($_POST['name']) ? $_POST['name'] : '');
$phone = (isset($_POST['phone']) ? $_POST['phone'] : '');
if(isset($_POST['submit']))
{
validate_input();
if(count($errors) != 0)
{
display_form();
}
else
{
echo "<b>OK! Go ahead and Process the form!</b><br/>";
}
}
else
{
display_form();
}
function validate_input(){
global $errors;
global $name;
global $phone;
if($name == '')
{
$errors['name'] = "<font color='red'>***Your name?***</font>";
}
if($phone == '')
{
$errors['phone'] = "<font color='red'>***Your phone?</font>";
}
}
function display_form(){
global $errors;
global $name;
global $phone;
?>
<b>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
What is your name?<br/>
<input type="text" name="name" value="<?php echo $name; ?>" /><br/>
<?php if (isset($errors['name'])) echo $errors['name']; ?><br/>
What is your phone number?<br/>
<input type="text" name="phone" value="<?php echo $phone; ?>" /><br/>
<?php if (isset($errors['phone'])) echo $errors['phone']; ?><br/>
<input type="reset" />
<input type="submit" name="submit" /><br/>
</form></b>
<?php
}
?>
</div>
</body>
</html>
Simply use isset($var); to avoid Undefined index: EROOR on php.
echo isset($_POST['name']);
echo isset($_POST['phone']);
wherever you need.

How to $_Post data from submit form PHP after validation

I just saw this codes from this website and thinking to implement it to my project however I cannot get my data on the next page. I am using the test.php as a index and submit.php as a page that will catch the post
here is the codes
test.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.
if (empty($_POST["firstName"])) {
$firstNameErr = "First name is required";
$valid = false; //false
}
else {
$firstName = test_input($_POST["firstName"]);
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
$valid = false;
}
else {
$lastName = test_input($_POST["lastName"]);
}
//if valid then redirect
if($valid){
header('Location: submit.php');
exit();
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Find Customer</h2>
<p><span class="error">* required</span></p>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
First Name: <input type="text" name="firstName" value="<?php echo $firstName; ?>"><span class="error">* <?php echo $firstNameErr; ?></span><br><br>
Last Name: <input type="text" name="lastName" value="<?php echo $lastName; ?>"><span class="error">* <?php echo $lastNameErr; ?><br><br>
<input type="submit">
</form>
</body>
</html>
submit.php
<?php
$test=$_POST['lastName'];
echo $test;
?>
Your form action should be the file where you want to get the form submitted values .
change this <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post"> to <form action="submit.php" method="post">

!empty() Parameter Misformatted?

I am building a form. I have set it so that when the submit button has been pressed, an HTML page with the data shows up. If submit has not been clicked, the form is displayed.
My issue is that when I add the !empty() parameters to if((isset($_POST['submit']), my PHP page shows no content whatsoever. I added the !empty() parameters to check if the submit button has been clicked AND all form fields are not empty, and form output is false. I'm thinking the formatting of the !empty() validation is incorrect. The form runs fine with out && (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['user_street']) && !empty($_POST['user_city']) && !empty($_POST['user_state']) && !empty($_POST['zip_code'])))
I've double checked and do not see any errors. Any insights to what might be the issue would be appreciated.
<?php
if((isset($_POST['submit']) && (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['user_street']) && !empty($_POST['user_city']) && !empty($_POST['user_state']) && !empty($_POST['zip_code']))) {
$first = $_POST['first_name'];
$last = $_POST['last_name'];
$street = $_POST['user_street'];
$city = $_POST['user_city'];
$state = $_POST['user_state'];
$zip = $_POST['zip_code'];
$output_form = false;
}
else {
$output_form = true;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
if($output_form) {
?>
<h1>PHP Sticky Form</h1>
<form action="<?= $_SERVER[ 'PHP_SELF' ]; ?>" method="post" name="userForm">
<p>First Name: <input type="text" id="first_name" name="first_name" value="<?=$first ?>" /></p>
<p>Last Name: <input type="text" id="last_name" name="last_name" value="<?=$last ?>" /></p>
<p>Street Address: <input type="text" id="user_street" name="user_street" value="<?=$street ?>" /></p>
<p>City: <input type="text" id="user_city" name="user_city" value="<?=$city ?>" /></p>
<p>State: <input type="text" id="user_state" name="user_state" value="<?=$state ?>" /></p>
<p>Zip Code: <input type="text" id="zip_code" name="zip_code" value="<?=$zip ?>" /></p>
<p><input type="submit" name="submit" /></p>
</form>
<?php
} else {
?>
<h1>Your Address Information</h1>
<p>NAME: <?= $first . ' ' . $last ?></p>
<p>STREET: <?= $street ?></p>
<p>CITY, STATE, ZIP: <?= $city . ' ' . $state . ", " . $zip ?></p>
<?php
}
?>
</body>
</html>
Your main problem there is that you are using && for checking values in $_POST,
if(isset($_POST['submit'] && (!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['user_street']) && !empty($_POST['user_city']) && ...
This means that if one value from the form (ex. $_POST['first_name'] is empty) then it will not show your output data.
You can do something like:
if(isset($_POST['submit'])){
//if $_POST['first_name'] is not empty, get value, else get error
$first = !empty($_POST['first_name']) ? $_POST['first_name'] : 'empty firstname';
//check other values as well
...
$output_form = false;
}else{
$output_form = true;
}
You are probably missing an extra ) after empty($_POST['zip_code']))).

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Categories