pure php prevent html input to save into text file - php

i would like to save all submitted data into text file.
there is a regex looking for any name error, if there is, there should be an error message AND!! that submission should not be captured into the text file.
result now: if i were to hit submit button even with name being numbers, i am able to submit and the error message did show up, however, it is being captured in the text file.
HOW can i stop it from saving the input if the condition is not met?
<p> <span class="required"> text boxes with * are required field </span></p>
<form method="post">
Name: <input type="text" id="name" name="name">
<span class="required"> * <?php echo $nameErr;?></span>
<br><br>
Phone Number: <input type="text" id="phoneno" name="phoneno">
<span class="required"> * <?php echo $phonenoErr;?></span>
<br><br>
E-Mail: <input type="text" id="email" name="email">
<span class="required"> * <?php echo $emailErr;?></span>
<br><br>
<input type="submit" id="submit" name="submit" value="submit"> <!--need to code submit alr will redirect to where-->
</form>
UPDATED MY CODE
if (isset($_POST['submit'])) {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phoneno"])) {
$phonenoErr = "Phone Number is required";
} else {
$phoneno = $_POST["phoneno"];
// check if name only contains letters and whitespace
if (!preg_match("/^[[0-9]{8}]*$/", $phoneno)) {
$phonenoErr = "Please key in 8 digits phone number";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email Address is required";
} else {
$email = $_POST["email"];
// check if name only contains letters and whitespace
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Wrong email format";
}
else {
/* to save html input into text file */
$name = "Seller Name: " . $_POST['name'] . "
";
$phoneno = "Phone Number: " . $_POST['phoneno'] . "
";
$email = "E-Mail: " . $_POST['email'] . "
";
$file = fopen("testing.txt", "a");
fwrite($file, $name);
fwrite($file, $phoneno);
fwrite($file, $email);
fclose($file);
}
}

You do not need an else statement. Right now your file checks "is a form submitted or not" and if it's not, then stuff will be saved. That doesn't make sense, right? You want to save only if the form was submitted! So don't use an else condition.
You can use an error variable to check if there is any error in any user input.
if (isset($_POST['submit'])) { //the user put in data and submitted the form
$error = 0; //no error yet
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$error = 1; //now there is an error
} else {
$name = $_POST["name"]; //be aware of security risks like SQL injection
}
//error checking for other inputs in the same way
//If there is no error at all, then save the input into a file
if ($error == 0) {
/* to save html input into text file */
$save = "Seller Name: " . $name;
$save .= "Phone Number: " . $phoneno;
$save .= "E-Mail: " . $email;
$file = fopen("testing.txt", "a");
fwrite($file, $save);
fclose($file);
}
}

You should put your writing file logic inside your success condition, without changing much of your code, it should be something like this:
$nameErr = $phonenoErr = $emailErr = "";
/*condition&regex to all text field*/
if (isset($_POST['submit']))
{
$name = $_POST["name"] ?? "";
if (empty($name)) {
$nameErr = "Name is required";
} else {
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if ($nameErr === "") {
$name = "Seller Name: ".$_POST['name']."";
$phoneno = "Phone Number: ".$_POST['phoneno']."";
$email = "E-Mail: ".$_POST['email']."";
$file=fopen("testing.txt", "a");
fwrite($file, $name);
fwrite($file, $phoneno);
fwrite($file, $email);
fclose($file);
}
}
Also note that there is no checks for other field (phoneno and email), so if they are not set, you will have error!

Related

PHP how to pass a variable from another page to a page that has a validation form

I want to pass a variable from another page to a page that has a validation form
Page1.php is the page contains the variable I want to pass. Let's say page2.php?var=$var
Page2.php is the page that has a validation form I want to store this variable from page1.php.
Let's say $var = $_REQUEST['var'];
The form of page2.php kind like this:
<?php
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
?>
</body>
</html>
When I pass the variable from page1.php to page2.php, first time is ok.
But as long as I hit "submit", the passed variable will be lost.
How could I keep this variable after multiple times of "submit"? so I can insert this variable along with the form to database
to validate the data in different files you just need to require the folder that accepts the form contents to the validation file

PHP Variable not storing value after submit

I have a simple PHP page, and am attempting to validate form input.
Upon hitting submit with invalid data, the inputted value is not being returned in my echo statement
I want to echo the input as the value so that the user can understand what they typed wrong. Below is my code;
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
<?php
// define variables and set to empty values
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<!--Begin HTML Form-->
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr;?></span><br> <!--<p class='spacerLine'></p>-->
<input type="text" class="largeInput" name="contactFirstName" value="<?php echo $contactFirstName;?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php echo $contactEmail;?>">
<br><br>
<?php echo "TEST" . $contactEmail;?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php echo $retailerID;?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Any thoughts? I'm new to PHP but have been following the W3 tutorial pretty tightly. Could it be my classes throwing things off? Or did I just mess up a variable name?
Thanks for all help
I want to echo the input as the value so that the user can understand what they typed wrong.
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
First of all, echo $_POST values instead of $contactFirstName, $contactEmail etc. because these values are available only after it crosses all the validation steps.
Second, there's no function named test_input() in your code, or may be it is defined somewhere else.
And finally, look at this statement here:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { ..
There's no variable named $email in your code. It should be:
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) { ..
So your code should be like this:
<?php
function test_input($string){
// your code
}
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr; ?></span><br>
<input type="text" class="largeInput" name="contactFirstName" value="<?php if(isset($_POST['contactFirstName'])){ echo $_POST['contactFirstName']; } ?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; } ?>">
<br><br>
<?php
echo "TEST ";
if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; }
?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php if(isset($_POST['retailerID'])){ echo $_POST['retailerID']; } ?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Here's the reference for isset() function:
isset()
Sidenote: Even though this answer will work you temporarily, but you should definitely look at how to strictly validate form inputs using regex.
The below line validates the value of the variable $email, but i can't see anywhere in your code where does that variable get set a value, that can be the first step in fixing the issue.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
You are not defining test_input() function and $email is not defined in this line:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
This code works for me so far:
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = $_POST["contactFirstName"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = $_POST["contactEmail"];
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = $_POST["retailerID"];
}
}

PHP script not validating input

Why is this script not validating e-mail address, name and phone number? It is sending the e-mail, but not notifying me of the intentional errors in the input fields. (This script is called from html form tag).
<?php
// define variables and set to empty values
$emailErr = $nameErr = $phoneErr = "";
$email = $name = $phone = $message = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number is valid (this regular expression also allows dashes in the phone number)
if (!preg_match("/^[0-9+'('+')'+ '-' ]*$/",$phone)) {
$phoneErr = "Invalid Phone Number";
}
}
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
mail( "omitted#omitted.com", "Contact Us Inquiry",
$message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}
?>
updated 6/23/15 almost midnight EDT
Form now validates input, but I want it prettier.
Posting contents of HTML form tag and script tag to show you that I want the email, name and phone number errors to appear to the right of the input boxes for those fields and if there are errors, I want to stay on the Contact_Us page. How do I do that? (Also posting working php script below the HTML form contents.)
In Head tag:
<style>
.error {color: #00a261;}
</style>
In Body tag:
<p><span class="error">* required field. </span></p>
<form method="post" name="contact_us_form" action="contact_us_e_mail.php">
<div align="center">
Email: <input name="email" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php
echo $emailErr; ?>
</span><br /><br />
Name: <input name="name" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php echo $nameErr; ?>
</span><br /><br />
Phone: <input name="phone" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php echo $phoneErr; ?>
</span><br /><br />
Message:<br />
<textarea name="message" border-style: solid style="border-color:#00a261" rows="15" cols="80">
</textarea>
<br />
<input type="submit" value="Submit"/>
</form>
Revised php script (called contact_us_e_mail.php):
<?php
// define variables and set to empty values
$emailErr = $nameErr = $phoneErr = "";
$email = $name = $phone = $message = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format. Please use browser's back button and correct.";
}
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed in Name. Please use browser's back button and correct.";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number is valid (this regular expression also allows dashes in the phone number)
if (!preg_match("/^[0-9+'('+')'+'-']*$/",$phone)) {
$phoneErr = "Invalid Phone Number. Please use browser's back button and correct.";
}
}
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
mail( "omitted#omitted.com", "Contact Us Inquiry",
$message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}else{
echo $emailErr, "<br />";
echo $nameErr, "<br />";
echo $phoneErr, "<br />";
//$errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
//header( "Location: http://omitted.com/Contact_Us.html" );
}
}
?>
Well you are setting the variables $nameErr, $phoneErr, $emailErr but you are never testing them.
You should wrap your mail statement in an if like this:
if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
mail( "omitted#omitted.com", "Contact Us Inquiry", $message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}else{
$errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
header( "Location: http://omitted.com/errors.php?errorList=" . $errorList );
}
Here's one approach to cracking that particular nut. The key is to check for the existance of the form's vars at the beginning of the script, before deciding what to present to the user. Yet another alternative would be to submit the form using the FormData object and AJAX. You could return a JSON object and then with JS on the client-side, decide whether to hide/show error messages and to re-direct to another page upon success, if desired.
The way that the die functions is one of the important keys to such an approach. As mentioned in the comments, it stops any further processing of the file - whether it be simply emitting html or if it be evaluating php code.
If the 'validation' (that I dont perform) fails, you'll get an asterisk next to the fields with problems. It will also throw the acceptable fields back into their inputs in the form, avoiding the need to type all of the info again for the sake of an error in just one of the inputs.
Just throw it onto a server and have a play. I'm a bit in two minds about such an approach. On one hand, it ties everything all together in a single location. On the other hand, you can end up with 4 languages in a single file (php,html,css,js) and something that can fairly quickly become a little er, unpleasant to maintain.
test.php
<?php
/*
sample that contains a form that will sumbit to itself
*/
// nothing entered in the POST array - this means the page has been loaded as a result of a request originating
// somewhere _other_ than the form in this page.
// we'll need to display the page ready for a 'first-visit'
if (count($_POST) == 0)
{
//echo ('$_POST array is empty!<br>');
$username = $email = $message = '';
}
// no validation here, I'm assuming all are okay. You need to validate for yourself in this block of code.
// you'll notice that submitting an empty form gives us 3 vars in the POST array, all of which are empty strings
else
{
$username = $email = $message = '';
if (isset($_POST['username']) == true)
$username = $_POST['username'];
if (isset($_POST['email']) == true)
$email = $_POST['email'];
if (isset($_POST['message']) == true)
$message = $_POST['message'];
// use this block or the 7 lines above - they have the same effect.
/*
$username = isset($_POST['username']) == true ? $_POST['username'] : "";
$email = isset($_POST['email']) == true ? $_POST['email'] : "";
$message = isset($_POST['message']) == true ? $_POST['message'] : "";
*/
if ( strlen($username) == 0)
$usernameNotPresent = true;
if ( strlen($email) == 0)
$emailNotPresent = true;
if ( strlen($message) == 0)
$messageNotPresent = true;
if (( isset($usernameNotPresent)==false) && (isset($emailNotPresent)==false) && (isset($messageNotPresent) == false))
{
doSendMail();
// execution/parsing of the file will stop here. This has 2 effects.
// 1. Any further php code wont be interpreted and then run
// 2. Any html that follows a call to die wont be shown.
// Therefore, if we get here that means we've sent the email and there's no use in showing the
// email form.
// provided nothing has been output yet, you could also re-direct to another page with a call
// to the function header
die;
}
}
function doSendMail()
{
// ToDo:
// send the email here
// print a message telling the user of the outcome of trying to send the email.
echo "<p>Email successfully sent, please check your inbox</p>";
}
?>
<!doctype html>
<html>
<head>
<script>
</script>
<style>
.wrapper
{
display: inline-block;
}
#myForm
{
text-align: center;
}
#myForm > input, #myForm > textarea
{
/* display: block; */
margin-bottom: 16px;
width: 170px;
text-align: left;
}
#myForm > input[type='submit']
{
width: 50%;
text-align: center;
}
</style>
</head>
<body>
<div class='wrapper'>
<form id='myForm' method='post' action='' > <!-- an empty action attribute submits the form back to itself -->
<?php
if (isset($usernameNotPresent))
echo "<input type='text' name='username' placeholder='enter username'><span class='error'>*</span></br>";
else
echo "<input type='text' name='username' placeholder='enter username' value='$username'></br>";
?>
<?php
if (isset($emailNotPresent))
echo "<input type='text' name='email' placeholder='enter email address'><span class='error'>*</span></br>";
else
echo "<input type='text' name='email' placeholder='enter email address' value='$email'></br>";
?>
<?php
if (isset($messageNotPresent))
echo "<textarea name='message' placeholder='enter your message'></textarea><span class='error'>*</span></br>";
else
echo "<textarea name='message' placeholder='enter your message'>$message</textarea></br>";
?>
<div><input type='submit' value='GO'/></div>
</form>
</div>
</body>
</html>

Failure message doesn't display when invalid PHP form is submitted

I'm having some difficulty with a PHP form, the problem being that my confirmation message displays even when the form fields have not been validated.
If the form has not been validated, I would like to display an alternative message that explains to the user that something went wrong and their message was not sent.
Unfortunately, my understanding of PHP is only as good as the tutorials I've taken in trying to put this form together so I'm a bit stuck! Would someone be kind enough to explain to me what I am doing wrong?
Here's the code:
<?php
ini_set('display_errors', 'On');
//Defines error variables and sets to empty
$senderErr = $senderEmailErr = $messageErr = "";
//Defines text entry variables and sets to empty
$sender = $senderEmail = $message = "";
//Defines failure/confirmation messages and sets to empty
$thankYou = "";
$formFail = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["sender"])) {
$senderErr = "Name is required";
} else {
$sender = test_input($_POST["sender"]);
// Checks that name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$sender)) {
$senderErr = "Only letters and white space allowed";
}
}
if (empty($_POST["senderEmail"])) {
$senderEmailErr = "Email is required";
} else {
$senderEmail = test_input($_POST["senderEmail"]);
// Checks if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$senderEmail)) {
$senderEmailErr = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$messageErr = "You haven't written anything";
} else {
$message = test_input($_POST["message"]);
}
if($_POST["submit"]) {
$recipient="me#email.com";
$subject="enquiry";
$sender=$_POST["sender"];
$senderEmail=$_POST["senderEmail"];
$message=$_POST["message"];
$mailBody="Name: $sender\nEmail: $senderEmail\n\n$message";
mail($recipient, $subject, $mailBody, "From: $sender <$senderEmail>");
$thankYou = "Thanks for your message. We'll get back to you shortly";
}
else {
$formFail = "Oops. Something went wrong. Please fill out the required fields.";
}
}
?>
I think it has something to do with the fact that I'm not setting the right conditions for failure. Problem is, I'm not quite sure where to start. Apologies for being a noob. Help appreciated. Thanks.
Edit - here's the HTML in response to Fred's question about whether the elements are named:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Name:</label></br>
<input type="text" name="sender"></br>
<span class="error">* <?php echo $senderErr;?></span>
</br>
<label>Email address:</label></br>
<input type="text" name="senderEmail"></br>
<span class="error">* <?php echo $senderEmailErr;?></span>
</br>
<label>Message:</label></br>
<textarea rows="5" cols="20" name="message"></textarea></br>
<span class="error">* <?php echo $messageErr;?></span>
<input type="submit" name="submit" value="submit"></br>
</form>
<span><?php echo $thankYou;?></span>
<span><?php echo $formFail;?></span>
Replacing if($_POST["submit"]) with if(($_POST["submit"]) && !empty($_POST["sender"]) && !empty($_POST["senderEmail"]) && !empty($_POST["message"])) will fix the problem.
Using PHP's empty() function, ensures that if something is left "empty" and used in a conditional statement, will not execute until all conditions are met.
All being the && (logical) operator.

PHP form verification

I'm new to PHP so please be gentle!
I'm trying to build a simple PHP form validation with an error message/confirm message. When I submit the form, it's supposed to check if fields are empty and display the corresponding message. But it keeps giving me an error and I have no idea why:
Parse error: syntax error, unexpected T_IF in process.php on line 6
Here's process.php code:
<form action="process.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST[fname]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST[lname]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}   
}
if ($_POST[email]){
$email = $_POST[email]; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>
You forgot to add " on post array that is the reason for your error $_POST[lname] change to $_POST['lname']; . Pass string to your $_POST[];
if ($_POST["fname"]){
$fname = $_POST[fname]; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST["lname"]){
$lname = $_POST[lname]; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST["email"]){
$email = $_POST["email"]; //If email was entered
}
Some of your $_POST variables were missing single quotation marks, which is probably what caused the errors. However, generally speaking, there are other code suggestions which I've layed out.
I restructured your code to be more scalable and follow better practice with the following enhancements:
Form values will remember their previous value and not erased on each post.
Removed the 'submitted' field and replaced with if (!empty($_POST)) {} to make sure form was posted.
Moved error messages into an array. This is more maintainable and readable to my taste (imagine having 15+ fields to test for).
Added validate() function to run on your validation tests.
Removed variable assignments ($fname = $_POST['fname']) since they were not used except for the validation, which can access them directly.
Moved all tests inside the main if statement.
Hope this helps!
<form action="process.php" method="post">
First Name: <input type="text" name="fname" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : ''?>"><br>
Last Name: <input type="text" name="lname" value="<?php echo isset($_POST['lname']) ? $_POST['lname'] : ''?>"><br>
E-mail: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''?>"><br>
<input type="submit">
</form>
<?php
//If form was submitted
if (!empty($_POST)) {
$errors = array();
if (empty($_POST['fname'])){
$errors[] = 'First name must be entered.';
}
if (empty($_POST['lname'])){
$errors[] = 'Last name must be entered.';
}
if (empty($_POST['email'])){
$errors[] = 'Email address must be entered.';
}
if ($errors){ //If any errors display them
$error_msg = implode('<br>',$errors);
echo "<div class=\"box red\">$error_msg</div>";
}
//If all fields present
elseif (validate()){
//Do something
echo "<div class=\"box green\">Form completed and validated!</div>";
}
}
function validate() {
/*you can run all your validation methods here, such as check for length, regexp email verification, etc.*/
$validated = false;
if ($_POST['fname'] && $_POST['lname'] && $_POST['email']) {
$validated = true;
}
return $validated;
}
?>
For the $_POST variables use syntax as $_POST['your variable name']
I corrected your code as below:
<form action="test.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
E-mail: <input type="text" name="email"><br>
<input type="hidden" name="submitted" value="1">
<input type="submit">
</form>
<?php
//If form was submitted
if ($_POST['submitted']==1) {
$errormsg = ""; //Initialize errors
if ($_POST['fname']){
$fname = $_POST['fname']; //If fname was entered
}
else{
$errormsg = "Please enter first name";
}
if ($_POST['lname']){
$lname = $_POST['lname']; //If lname was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . ", last name";
}
else{
$errormsg = "Please enter last name";
}
}
if ($_POST['email']){
$email = $_POST['email']; //If email was entered
}
else{
if ($errormsg){ //If there is already an error, add next error
$errormsg = $errormsg . " & email";
}else{
$errormsg = "Please enter email";
}
}
}
if ($errormsg){ //If any errors display them
echo "<div class=\"box red\">$errormsg</div>";
}
//If all fields present
if ($fname && $lname && $email){
//Do something
echo "<div class=\"box green\">Form completed!</div>";
}
?>
As Ohgodwhy said,
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.
And why are you using <input type="hidden" name="submitted" value="1">, this is not a good practice. Better use.
if($_SERVER['REQUEST_METHOD'] == "POST")
The issue here is a lack of register globals being enabled (which is a good thing in my eyes) and not using proper string encapsulation.
You need to change every existence of $_POST[word] to $_POST['word']. Note the '.
I am Using thing type of simple validation. Here is my javascript code:
var ck_name = /^[A-Za-z0-9 ]{3,50}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/;
var ck_mob = /^[0-9 ]{8,11}$/;
function validate(form){
var name = form.name.value;
var email = form.email.value;
var mob = form.mob.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Your valid Name .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Your must enter a valid email address.";
}
if (!ck_mob.test(mob))
{
errors[errors.length] = "Your valid Mobile Number.";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++)
{
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}

Categories