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']))).
Related
I'm creating a simple web app that calculates the age of when you're going to graduate. My program runs fine in eclipse but as soon as I push it to the server and push my button (submit) it redirects to a 404 error. I'm using ipages and I'm aware that they are using php 5.6. Any helpful tips would help out a ton.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<title>Graduation Calculator</title>
</head>
<body>
<img alt="Image goes here..." src="Balloon-Banner.jpg" width = "1050" height="180">
<form action="grad.php" method="POST">
<center>
<br>
<br>
<br>
<label><?php echo "Today is " . date("m/d/Y"); ?></label>
<br>
<br>
<br>
<label>Enter your birth year: </label>
<input type="text" name="birthYear" />
<label>Enter your graduation year: </label>
<input type="text" name="gradYear" />
<br>
<label>Enter your Birth Month: </label>
<input type = "text" name = "birthMonth"/>
<label> Enter your graduation month</label>
<input type = "text" name = "gradmonth" />
<br>
<label> Enter your birthday</label>
<input type = "text" name = "birthDay" />
<label>Enter your graduation day: </label>
<input type="text" name="gradday" />
<br>
<input type='submit' value='Graduation Age' id = 'submit' />
</center>
</form>
<?php
$submitted = ! empty ( $_POST );
if ($submitted == true)
{
$bYear = (int) $_POST ['birthYear'];
$gYear = (int) $_POST ['gradYear'];
$gMonth = (int) $_POST['gradmonth'];
$bMonth = (int) $_POST['birthMonth'];
$bday = (int) $_POST['birthDay'];
$gday = (int) $_POST ['gradday'];
$age = getAge($bYear, $gYear, $bMonth, $gMonth, $bday, $gday);
if($age!= NULL){
echo "You will be " . $age . " at your graduation.";
}
else{
echo "INVALID INPUT, PLEASE TRY AGAIN";
}
}
function getAge( $bYear, $gYear, $bMonth, $gMonth, $bday, $gday)
{
If($bYear> $gYear || $bMonth>12 || $gMonth >12 || $bday >31 || $gday >31 || $bYear == 0 || $gYear == 0 || $bMonth == 0 || $bday == 0 || $gMonth ==0|| $gday == 0){
return NULL;
}
$age = $gYear - $bYear;
if($bMonth == $gMonth){
if($bday <= $gday){
return $age;
}
else{
$age = $age-1;
return $age;
}
}
elseif($bMonth < $gMonth){
return $age;
}
else{
return $age-1;
}
return $age;
}
?>
</body>
</html>
If you're executing your front-end and back-end code in the same file, just keep it simple and just do it in the same file unless you have a framework.
Change <form action="grad.php" method="POST"> to <form method="POST">.
Should work, if not we'll try to work something out ;)
Remove the action="grad.php" from form. So it will submit to self.
I looked trough your pages and fixed my undefined index on username and password but now I get undefined variable. I had more code but decided to simplify it for the sake of testing and just echo it to see if anything changes and it doesn't.
<?php
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
}
echo $uname;
echo $password;
?>
I get this:
Notice: Undefined variable: uname in C:\xampp\htdocs\8\login.php on line 7
Notice: Undefined variable: pass in C:\xampp\htdocs\8\login.php on
line 8
I do not really understand what's wrong here. If needed here is my form page html.
<form id="login" method="post" action="login.php">
<div id="loginon">
<label for="username" style="color:#0F0; font-family:Arial, Helvetica, sans-serif;" >Username: </label>
<input type="text" id="username" name="username" />
<br />
<br />
<label for="password" style="color:#0F0; size:auto; font-family:Arial, Helvetica, sans-serif;">Password: </label>
<input type="password" id="password" name="password" />
<br />
<br />
<input type="image" src="http://www.clker.com/cliparts/2/G/4/v/K/E/submit-hi.png" border="0" width="180px" height="80px" alt="Submit" />
</div>
</form>
</body>
EDIT:
The further problem is connected to this so I think I am allowed to post it here.
if($username == "pikachu" || "cloud") {
$ucheck = "dobar";
} else {
$ucheck = "los";
}
if ($password == "123123" || "132132") {
$pcheck = "topar";
} else {
$pcheck = "losh";
}
if($ucheck == "dobar" && $pcheck == "topar") {
echo "Najjaci si!";
}
elseif ($ucheck == "dobar" && $pcheck == "losh") {
echo "Wimp.";
} elseif ($ucheck == "los" && $pcheck == "topar") {
echo "Fish.";
}
The problem is that it always echoes out "Najjaci si" no matter what I type in the previous form. Any ideas?
Since you have the variable decleration inside a logic (If), there is a chance that the variables are not set at all.
Try this
<?php
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
echo $uname;
echo $pass;
} else {
echo "No submit detected!";
}
?>
It also doesen't look like if you have an actual element named submit.
Try adding this:
<input type="submit" name="submit" value="Send my form" />
Now, your form contains an element named "submit" which will be send as a post parameter when the form is submitted.
I myself, in need of a framework, like doing like this:
$username = ( isset($_POST["username"]) && $_POST["username"] != "" ? $_POST["username"] : false );
$password = ( isset($_POST["password"]) && $_POST["password"] != "" ? $_POST["password"] : false );
if( !$username === false && !$password === false )
{
echo $username . " <br /> " . $password;
} else {
echo "No! :) ";
}
isset will check that variable is set or not and pass value in 0 or 1. So over here you need to do as
$uname = isset($_POST['username']) ? $_POST['username'] : '';
$pass = isset($_POST['password']) ? $_POST['password'] : '';
Notice: Undefined variable: pass in C:\xampp\htdocs\8\login.php on line 8
Its because you were echoing $password instead of $pass
Edited
Do it as
$uname = '';
$pass = '';
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
}
echo $uname;
echo $pass;
Try this
In form
<form id="login" method="post" action="login.php">
<div id="loginon">
<label for="username" style="color:#0F0; font-family:Arial, Helvetica, sans-serif;" >Username: </label>
<input type="text" id="username" name="username" />
<br />
<br />
<label for="password" style="color:#0F0; size:auto; font-family:Arial, Helvetica, sans-serif;">Password: </label>
<input type="password" id="password" name="password" />
<br />
<br />
<input type="submit" name="submit"/>
</div>
</form>
</body>
In login.php
<?php
if (isset($_POST['submit']))
{
$uname = $_POST['username'];
$pass = $_POST['password'];
}
echo $uname;
echo $pass;
?>
<html>
<?php
mysql_connect("localhost","root","");
mysql_select_db("demo");
if(isset($_POST['submit'])){
$post_name = $_POST['name'];
$post_gender = $_POST['gender'];
if($post_name==''){
echo "<div class='efe'>* All fields are mandatory...</div>" ;
}
else {
$insert_query = "insert into demo
(name,sex)
values('$post_name','$post_gender')";
if(mysql_query($insert_query)){
echo "<div class='efe ewffs6re'>Post successfully...</div>";
}
}
}
?>
<form method="post" class="iurtture4" align="left" enctype="multipart/form-data">
<span>Name</span><input type="text" name="name" /><br>
<span>Male</span><input type="radio" value="male"name="gender" /><br>
<span>Female</span><input type="radio" name="gender" value="female"placeholder="Enter"autocomplete="off"/><br>
<button name="submit">Submit</button>
</form>
An easy way to get values from an array ($_POST, $_GET....) is:
$post_name = isset($_POST['name']) ? $_POST['name'] : '';
$post_gender = isset($_POST['gender']) ? $_POST['gender'] : '';
It can be used without modifying other things in your code.
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>
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