I have a problem with preserving the values written inside a textfield, if an error occurs. I have 4 textfields, and if 1 is blank it needs to show a new form, with a error message and the input in the textfield from the previous file.
I guess it's the last part of my assignment_2.php where it's wrong.
assignment_1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="sendit.php" method="get">
<input type="text" name="name" placeholder="name"/>
<br>
<input type="text" name="adress" placeholder="adress"/>
<br>
<input type="text" name="city" placeholder="city"/>
<br>
<input type="text" name="zip" placeholder="zip"/>
<br>
<input type="submit" />
</form>
<br>
</body>
</html>
sendit.php
<?php
$name = $_GET['name'];
$adress = $_GET['adress'];
$city = $_GET['city'];
$zip = $_GET['zip'];
if (!isset($_GET['name']) || $_GET['name'] == '') {
header("Location: assignment_2.php?errmsg=1");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&name=$name");
}
if (!isset($_GET['adress'])|| $_GET['adress'] == '') {
header("Location: assignment_2.php?errmsg=2&adress=$adress");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&adress=$adress");
}
if (!isset($_GET['city'])|| $_GET['city'] == '') {
header("Location: assignment_2.php?errmsg=3&city=$city");
exit;
}
else {
header("Location: assignment_2.php?errmsg=1&city=$city");
}
if (!isset($_GET['zip'])|| $_GET['zip'] == '') {
header("Location: assignment_2.php?errmsg=4&zip=$zip");
exit;
}
else {
header("Location: assignment_2.php?errmsg=4&zip=$zip");
}
echo $name . "<br>" . $adress . "<br>" . $city . "<br>" . $zip
?>
assigment_2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// 1.0 Create a contactform containing name, address, city, zipcode
// Send it to a form handler
// If any of the form fields are not filled out, return to this page and
// display an error containing information on how to prevent the error
// 1.1 Preserve the input for the user
?>
<?php
if (isset($_GET['errmsg'])) {
$err = $_GET['errmsg'];
switch ($err) {
case 1:
$err_msg = 'Missing navn';
break;
case 2:
$err_msg = 'Missing adress';
break;
case 3:
$err_msg = 'Missing city';
break;
case 4:
$err_msg = 'missing zip';
break;
default:
$err_msg = 'I just dont like you';
break;
}
echo '<div class="error">' . $err_msg . '</div>';
}
?>
<form action="sendit.php" method="get">
<input type="text" name="name" placeholder="name" <?php
if (isset($_GET['name'])) echo 'value="' .$_GET['name'] .'"';
?> />
<br>
<input type="text" name="adress" placeholder="adress" <?php
if (isset($_GET['adress'])) echo 'value="' .$_GET['adress'] .'"';
?>/>
<br>
<input type="text" name="city" placeholder="city" <?php
if (isset($_GET['city'])) echo 'value="' .$_GET['city'] .'"';
?>/>
<br>
<input type="text" name="zip" placeholder="zip" <?php
if (isset($_GET['zip'])) echo 'value="' .$_GET['zip'] .'"';
?>/>
<br>
<input type="submit" />
</form>
</body>
</html>
I will probably handle first client side validation, so the form will not submit until all inputs get fill, then I will do some server side validation and sanitization. BTW you don't need to have assigment2.
Keep things simple!
For starters, try working on only one file, and put your errors into an array.
Then try shortening your code, and to never "copy & paste" code.
On modern sites, developpers use frameworks to validate forms,
Keep playing with this one until it works like you want, and have a look at Symfony or Zend Framework form validation.
<?php
$errors = array();
if (isset($_GET['submitted'])) {
if (!isset($_GET['name']) || $_GET['name'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['adress']) || $_GET['adress'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['city']) || $_GET['city'] == '')
$errors[] = 'Missing navn'
if (!isset($_GET['zip']) || $_GET['zip'] == '')
$errors[] = 'Missing navn'
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
if (count($errors) !== 0)
echo '<div class="error">' . implode("<br>", $errors) . '</div>';
?>
<form action="" method="get">
<input type="hidden" name="submitted" value="1" />
<input type="text" name="name" placeholder="name" value="<?php echo isset($_GET['name']) ? $_GET['name'] : '' ?>" />
<br>
<input type="text" name="adress" placeholder="adress" value="<?php echo isset($_GET['adress']) ? $_GET['adress'] : '' ?>" />
<br>
<input type="text" name="city" placeholder="city" value="<?php echo isset($_GET['city']) ? $_GET['city'] : '' ?>" />
<br>
<input type="text" name="zip" placeholder="zip" value="<?php echo isset($_GET['zip']) ? $_GET['zip'] : '' ?>" />
<br>
<input type="submit" />
</form>
<br>
</body>
</html>
Related
I've tried a few methods found on this site regarding the prevention of form resubmission. However, the redirection function doesn't trigger for some reason.
May I know what i'm doing wrong and how i can fix it?
<?php
if(isset($_POST['bookingsubmit']))
{
$error = '0';
require_once("makebooking.php");
$i_username = $_SESSION['username'];
$i_slotno = isset($_POST['slotinput']) ? $_POST['slotinput'] : '';
$i_vehicleno = isset($_POST['vehiclenoinput']) ? $_POST['vehiclenoinput'] : '';
$i_vehicletype = isset($_POST['vehtype']) ? $_POST['vehtype'] : '';
$i_spacesreq = isset($_POST['spaceinput']) ? $_POST['spaceinput'] : '';
$error = makebooking($i_username,$i_slotno,$i_vehicleno,$i_vehicletype,$i_spacesreq);
}
?>
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Make a booking</title>
</head>
<body>
<div id="makebookingsection">
<form id="makebookingform" method="post" action="">
<h4>Book a time</h4>
<p>Name : <?php echo $_SESSION['username']?></p>
<p>Enter Slot Number : <input type="number" name="slotinput"></p>
<p>Vehicle No. : <input type="text" name="vehiclenoinput"></p>
<p>Vehicle Type : <input type="radio" name="vehtype" value="Truck">Truck
<input type="radio" name="vehtype" value="Trailer">Trailer</p>
<p>Spaces Required : <input type="number" name="spaceinput"></p>
<input name="bookingsubmit" type="submit" value="Book" />
<?php
if(isset($_POST['bookingsubmit']))
{
header("Location: " . $_SERVER['REQUEST_URI']);
}
?>
</form>
</div>
I assume you are trying to implement a Post/Redirect/Get (PRG) Pattern. For the Redirect part, you have to send the header before any output is sent to the user agent. To avoid caching, use 303 response code.
<?php
if(isset($_POST['bookingsubmit']))
{
$error = '0';
require_once("makebooking.php");
$i_username = $_SESSION['username'];
$i_slotno = isset($_POST['slotinput']) ? $_POST['slotinput'] : '';
$i_vehicleno = isset($_POST['vehiclenoinput']) ? $_POST['vehiclenoinput'] : '';
$i_vehicletype = isset($_POST['vehtype']) ? $_POST['vehtype'] : '';
$i_spacesreq = isset($_POST['spaceinput']) ? $_POST['spaceinput'] : '';
$error = makebooking($i_username,$i_slotno,$i_vehicleno,$i_vehicletype,$i_spacesreq);
header("Location: " . $_SERVER['REQUEST_URI'], true, 303);
exit;
}
else {
?>
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Make a booking</title>
</head>
<body>
<div id="makebookingsection">
<form id="makebookingform" method="post" action="">
<h4>Book a time</h4>
<p>Name : <?php echo $_SESSION['username']?></p>
<p>Enter Slot Number : <input type="number" name="slotinput"></p>
<p>Vehicle No. : <input type="text" name="vehiclenoinput"></p>
<p>Vehicle Type : <input type="radio" name="vehtype" value="Truck">Truck
<input type="radio" name="vehtype" value="Trailer">Trailer</p>
<p>Spaces Required : <input type="number" name="spaceinput"></p>
<input name="bookingsubmit" type="submit" value="Book" />
</form>
</div>
<?php
}
?>
You should add header() before you start rendering HTML, as your code seems that there is no meaning to use it in middle of HTML.
<?php
if(isset($_POST['bookingsubmit']))
{
$error = '0';
require_once("makebooking.php");
$i_username = $_SESSION['username'];
$i_slotno = isset($_POST['slotinput']) ? $_POST['slotinput'] : '';
$i_vehicleno = isset($_POST['vehiclenoinput']) ? $_POST['vehiclenoinput'] : '';
$i_vehicletype = isset($_POST['vehtype']) ? $_POST['vehtype'] : '';
$i_spacesreq = isset($_POST['spaceinput']) ? $_POST['spaceinput'] : '';
$error = makebooking($i_username,$i_slotno,$i_vehicleno,$i_vehicletype,$i_spacesreq);
}
if(isset($_POST['bookingsubmit']))
{
header("Location: " . $_SERVER['REQUEST_URI']);
}
?>
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Make a booking</title>
</head>
<body>
<div id="makebookingsection">
<form id="makebookingform" method="post" action="">
<h4>Book a time</h4>
<p>Name : <?php echo $_SESSION['username']?></p>
<p>Enter Slot Number : <input type="number" name="slotinput"></p>
<p>Vehicle No. : <input type="text" name="vehiclenoinput"></p>
<p>Vehicle Type : <input type="radio" name="vehtype" value="Truck">Truck
<input type="radio" name="vehtype" value="Trailer">Trailer</p>
<p>Spaces Required : <input type="number" name="spaceinput"></p>
<input name="bookingsubmit" type="submit" value="Book" />
</form>
</div>
You've put HTML contentbefore the header.Headers should be used before returning any output.
I'm having a hard time figuring how to fix this notification. I already did it but the result was the code didn't work. My logic is not that high here is the code:
Here is the error.
Would you also explain why the gender is undeinfed but the textbox and textarea was just fine?
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$x=$_POST['name'];
$y=$_POST['email'];
$z=$_POST['website'];
$c=$_POST['comment'];
$v=$_POST['gender'];
if($x == '' or $y == '' or $z==''or $c=='' or $v==''){
echo "* required all fields";
}else{
$result=$x.'<br>'.$y.'<br>'.$z.'<br>'.$c.'<br>'.$v;
}
}
?>
<form action="" method="post">
NAME:<input type="text" name="name"><br><br>
EMAIL:<input type="text" name="email"><br><br>
WEBSITE:<input type="text" name="website"><br><br>
<textarea name="comment" rows="5" cols="40"></textarea><br><br>
GENDER:<input type="radio" name="gender" value="Male">MALE
<input type="radio" name="gender" value="Female">Female<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h3>YOUR INPUT:</h3>";
echo $result;
?>
</body>
</html>
if($x == '' ||$y == '' || $z=='' || $c=='' || $v==''){
echo "* required all fields";
}else{
You cant user or man check the PHP manual
try this way
if(($x="" || empty($x))&&($y="" || empty($y))&&($z="" || empty($z)))
{
echo "* required all fields";
}
may be it will help
What you need is a JS function to validate your radio buttons at first, or you could also use the HTML attribute required (I have written both of them) followed by only a few if-statements This should work just fine.
<!DOCTYPE HTML>
<html>
<head>
<script>
function validateForm(){
for(i=0; i<document.form.radios.length; i++){
if(document.form.radios[i].checked==false){
c=1;
}
else{
c=0;
break;
}}
if(c==1){
alert('Please select an option');
}
}
</script>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$x=$_POST['name'];
$y=$_POST['email'];
$z=$_POST['website'];
$c=$_POST['comment'];
if($x == '' or $y == '' or $z==''or $c=='')
{ echo "* required all fields";
}else{
$result=$x.'<br>'.$y.'<br>'.$z.'<br>'.$c;
}
}
?>
<form action="" method="post">
NAME:<input type="text" name="name"><br><br>
EMAIL:<input type="text" name="email"><br><br>
WEBSITE:<input type="text" name="website"><br><br>
<textarea name="comment" rows="5" cols="40"></textarea><br><br>
<input type="radio" name="gender" value="Male" required /> Male
<input type="radio" name="gender" value="Female" /> Female
<input type="submit" name = "submit" value="SAVE" />
</form>
<?php
if(isset($_POST['submit']))
{
if(!($x == '' or $y == '' or $z==''or $c=='')){
echo "<h3>YOUR INPUT:</h3>";
echo $result;
}else
echo "NOT ALL FIELDS WERE SELECTED.";}
?>
</body>
</html>
You have some undefined variables.In order to make it work try this:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$result = '';
$x = '';
$y = '';
$z = '';
$c = '';
$v = '';
if(isset($_POST['submit'])){
if(isset($_POST['name'])){
$x= $_POST['name'];
}
if(isset($_POST['email'])){
$y=$_POST['email'];
}
if(isset($_POST['website'])){
$z=$_POST['website'];
}
if(isset($_POST['comment'])){
$c=$_POST['comment'];
}
if(isset($_POST['gender'])){
$v=$_POST['gender'];
}
.......
But you should separate your HTML code from the PHP,
maybe creating and index.html and from.php file.
Keeping all into the same file is a very bad practice.
$v=isset($_POST['gender'])?$_POST['gender']:'';
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']))).
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
I'm trying to pass a value from a select input control on an HTML form.
When I hardcode it, it gets echoed, when not, all I get is this:
The invention type did not go through correctly.
Here is my page1.php:
<?php
session_start();
$_SESSION['invtype'] = $invtype;
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
if (isset($_POST['Submit'])) {
if ($_POST['firstname'] != "") {
$_POST['firstname'] = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
if ($_POST['firstname'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
if ($_POST['lastname'] != "") {
$_POST['lastname'] = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
if ($_POST['lastname'] == "") {
$errors .= 'Please enter a valid last name.<br/><br/>';
}
} else {
$errors .= 'Please enter your last name.<br/>';
}
if (!$errors) {header("location: offerform_switch.php");
}
else {
echo '<div style="color: red">' . $errors . '<br/>
</div>';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Offer Form, Part 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="inventron_sage_short.css" type="text/css" />
<link rel="stylesheet" href="form.css" type="text/css" />
</head>
<body>
<div id = "logo">
<img src = "img/top.jpg" alt = "logo" />
</div>
<div id = "wrapper">
<div id="stylized" class="myform">
<form id="form" action="page1.php" method="post">
<p>
<label for="firstname">FIRST NAME*:
</label>
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname?>" />
</p>
<p>
<label for="lastname">LAST NAME*:
</label>
<input type="text" name="lastname" id="lastname" value="<?php echo $lastname?>" />
</p>
<div id = "category">Categorize your invention:</div>
<div class="spacer"></div>
<p>
<select id="invtype" name="invtype">
<option value="0" selected="selected">Select type</option>
<option value="product">PRODUCT</option>
<option value="software">SOFTWARE</option>
</select>
<input type="submit" name="Submit" value="Next!" />
</div>
</div>
</body>
</html>
Here is my offerform_switch.php:
<?php
session_start();
// echo variable from the session, we set this on our other page
echo $_SESSION['invtype'];
$invtype = $_SESSION['invtype'];
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("mysql.myserver.com","myuser","mypassword"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("invention") or die("Unable to select database"); //select which database we're using
switch ($invtype){
case "product":
include("page2_product.php");
break;
case "software":
include("page2_software.php");
break;
default:
echo "The invention type did not go through correctly.";
}
?>
What am I doing wrong?
Thank you!
It should be
$_SESSION['invtype'] = $_POST['invtype'];
You're missing "session_id();" right below the "session_start();". I don't know why exactly it's required, but if I remember correctly, it is.