Why this validation code does not work as expected? - php

I have a form and the action of the for m is same page.
I am trying to :
Show a thanks message upon the successful form submission
Show error messages next to the field where the error is detected
All the above must be shown in the same page.
My code is :
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
else {
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
?>
I've limited the validation and showing only for first part in this QUESTION.
When I submit this form If there is NO any errors the I am getting the message Thanks, We have received your feed back
That's fine and works as expected.
When an error exists / the field Guest name is empty I am getting the message during the form submission Errors!
Please check the fields which have errors below. Error hints are in Red.
That's also fine.
But my form is just disappear when I get the above message. Why?
Also I want show that Please type your name! next to the field.

Try bellow code. I have removed else part and set flag with true/false to check from is valid or not.
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
$chkValidate = "true";
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
$chkValidate = "false";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';
$chkValidate = "false";
}
if($chkValidate == "true"){
echo 'Thanks, We have received your feed back';
}
}
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?php if(!empty($errors) && $chkValidate != "false") { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
?>

Just remove else condition cause actually your form will not be display if $_POST["Ask_the_Question"] is set
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>

The reason why is here:
<?php
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
} else {
// your form code will never be called if $_POST['Ask_the_Question'] is set
TO do what you want to achieve you probably want to do something like this instead:
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
} else { ?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
}
?>

Other answers are fine, but just to clarify what happens.
But my form is just disappear when I get the above message. Why?
Your form disappear because if you pass the first if you can't get to your else.
if (isset($_POST["Ask_the_Question"])) {
...
} else {
xxx;
}
That means if you want to see your form you have to put it somewhere it can be shown like elseif (with more restrictions), or ifs inner or outer.
if (isset($_POST["Ask_the_Question"]) && empty($errors)) {
...
} elseif (isset($_POST["Ask_the_Question"]) && !empty($errors)) {
...
} else {
...
}
Also I want show that Please type your name! next to the field.
To show all errors you could use eg. foreach anywhere you want to show them.
foreach ($errors as &$error) {
echo "Error: $error<br />\n";
}
Btw be careful with the empty(); function.

Related

Not all variables passed in POST [duplicate]

This question already has answers here:
Posting input type file problem No Value posted
(2 answers)
Closed 3 years ago.
I'm working on a (supposedly) simple page and script to send an email with an attachment, but have run into a problem where the last value is not sent in POST. Danged if I can figure it out.
The HTML from the sending page is:
<form action="contact_reply.php" method="post" name="form1" required="required" id="form1" enctype="multipart/form-data" >
<p>
<input type="hidden" name="PageURL" value="<?php echo GetSelfURL() ?>" />
</p>
<p>Your Name<br />
<span id="sprytextfield1">
<input name="MSG_Name" type="text" required="required" id="MSG_Name" tabindex="1" size="70" maxlength="70" />
</span>
</p>
<p>Your Email Address<br />
<span id="sprytextfield2">
<input name="MSG_Email" type="text" required="required" id="MSG_Email" tabindex="2" size="70" maxlength="70" />
</span>
</p>
<p>Subject<br />
<span id="sprytextfield3">
<input name="MSG_Subject" type="text" required="required" id="MSG_Subject" tabindex="3" size="70" maxlength="70" />
</span>
</p>
<p>Message<br />
<span id="sprytextarea1">
<textarea name="MSG_Text" required="required" id="MSG_Text" cols="70" rows="5" tabindex="4"></textarea>
</span>
</p>
<?php
if ($Allow_Attachments)
{
?>
<p>Attachment (images only):
<input name="MSG_Attachment" type="file" id="MSG_Attachment" tabindex="5" accept="image/*" multiple >
</p>
<?php
}
?>
<p align="center">
<input
type="submit"
name="Contact_SendBtn"
id="Contact_SendBtn"
value="Submit"
tabindex="5"
vakue="send"
style="width:60px"/>
</p>
</form>
The php on the receiving end is:
function CheckMessageInfo()
{
global $MSG_Name, $MSG_Email, $MSG_Subject, $MSG_Text, $MSG_Attachment, $MSG_Error;
$MSG_Error = '';
echo "<p>".var_dump($_POST)."</p>";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["MSG_Name"]))
{
$MSG_Error .= "A name is required. ".PHP_EOL;
}
else
{
$MSG_Name = test_input($_POST["MSG_Name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$MSG_Name))
{
$MSG_Error .= "Only letters and spaces are allowed in the name. ".PHP_EOL;
}
}
if (empty($_POST["MSG_Email"]))
{
$MSG_Error .= "An email address is required. ".PHP_EOL;
}
else
{
$MSG_Email = test_input($_POST["MSG_Email"]);
if (!filter_var($MSG_Email, FILTER_VALIDATE_EMAIL))
{
$MSG_Error .= "Invalid email format. ".PHP_EOL;
}
}
if (empty($_POST["MSG_Subject"]))
{
$MSG_Error .= "A subject for the message is required. ".PHP_EOL;
}
else
{
$MSG_Subject = filter_var($_POST["MSG_Subject"],FILTER_SANITIZE_STRING);
}
if (empty($_POST["MSG_Text"]))
{
$MSG_Error .= "The message's text is required. ".PHP_EOL;
}
else
{
$MSG_Text = filter_var($_POST["MSG_Text"],FILTER_SANITIZE_STRING);
}
if (empty($_POST["MSG_Attachment"]))
{
$Allow_Attachments = FALSE;
}
else
{
$MSG_Attachment = $_POST["MSG_Attachment"];
}
return TRUE;
}
else
{
return FALSE;
}
}
The var_Dump line give me this:
array(6) {
["PageURL"]=> string(39) "www.vintagebankantiques.net/contact.php"
["MSG_Name"]=> string(4) "Mike"
["MSG_Email"]=> string(21) "me#myemail.com"
["MSG_Subject"]=> string(4) "test"
["MSG_Text"]=> string(21) "improved echo $_POST."
["Contact_SendBtn"]=> string(6) "Submit"
}
The "MSG_Attachment" variable is not listed. Where did it go?
You can get value of MSG_Attachment by
$_FILES['MSG_Attachment']["tmp_name"]
//if MSG_Attachment is array type
$_FILES['MSG_Attachment']["tmp_name"][0]
$_FILES['MSG_Attachment']["tmp_name"][1]
since MSG_Attachment input type is file, you can not get in POST.
you can also refer this link

php get the value from hidden field after redirect

member.php
<?php
if(isset($_POST['submit']))
{
$membername = $_POST['membername'];
if(empty($membername))
{
$errors .= "Please enter member name<br />";
}
if($errors)
{
$action = $_POST['submit'];
echo $errors;
displayForm();
}
else
{
?>
<input type="hidden" name="mname" value="<?php echo $_POST['membername']; ?>" />
<?php
$action = $_POST['submit'];
header("Location: commit.php?action=$action");
exit();
}
}
else
{
displayForm();
}
?>
<?php
function displayForm()
{
?>
<form action = "member.php" action="post">
Member Name <input type="text" name="membername" value="<?php if(isset($row['name'])) echo $row['name'];
else echo ''; ?>" /><br /><input type="text" name="membername" value=
<input type="submit" name="submit" name="add" />
</form>
<?php
}
?>
Commit.php
<?php
echo $_POST['mname']; //HERE
?>
I want to pass the hidden value from member.php. When I run commmit.php, I want to get hidden field value. However, the error is the following:
**Undefined index: mname in member.php in commit.php.
What am I doing wrong?

Passing PHP variable data onto another page after validation

While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';

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.

Make errors show on top of a form

How do I make error show on top of form so that if $user->success == true, it wont show my form then. Removing that last else would help, but then form shows after success. One way is to redirect that. Maybe tehre
if (isset($_POST["submit"]))
{
if ($_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
$User->signin($_POST['username'], $_POST['password']);
}
else
$User->CheckUser();
if ($User->success == true) {
include ('in.php');
}
if ($User->error)
echo "<p>" . $User->error . "</p>";
else
echo 'Don\'t process form';
$_SESSION["formid"] = md5(rand(0,10000000));
} else {
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input id="username" name="username" type="text" /><br />
Password:
<input id="password" name="password" type="password" /><br />
<input type="hidden" name="formid" value="<?php echo $_SESSION["formid"]; ?>" />
<input type="submit" name="submit" />
<br />
Register
</form>
<?php }?>
Perhaps the simplest approach is to just create a variable $show_form to use to determine whether form is to be shown,
$show_form = true;
if(isset($_POST['submit'])) {
// do your form processing here.
// If you decide everything is good and you don't want to show the form,
// just add this line:
$show_form = false;
} // don't use else here
if (true === $show_form) {
?>
<form>...</form>
<?
}
?>
add this code before your form tag
<?php if (isset($User->error) AND $User->error)?>
<p><?php echo $User->error?></p>
<?php?>

Categories