Indicating Required Fields in PHP - php

I'm trying to create a PHP file of a process form that indicates the required fields when processed. The code that I have is:
<html>
<head>
<style type="text/css">
.error{color: #FF0000;}
</style>
</head>
<body>
<?php
if(isset($_POST['fullname']) && $_POST['fullname'] != "") {
$fullname = $_POST['fullname'];
}
if(isset($_POST['email']) && $_POST['email'] != "") {
$email = $_POST['email'];
}
if(isset($_POST['feedback']) && $_POST['feedback'] != "") {
$text= $_POST['feedback'];
}
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == POST) {
if (empty($_POST["fullname"])){
$nameErr = "Name is required";
} else {
$name = test_input($_POST["fullname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}
?>
<h1>Customer Feedback</h1>
<p1>Please tell us what you think</p1><br><br>
<form method='POST' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>' >
<p1>Your name:</p1><br>
<input type="text" name="fullname" value="<?php echo $fullname; ?>"><br><br>
<p1>Your email address:</p1><br>
<input type="text" name="email" value="<?php echo $email; ?>"><br><br>
<p1>Your feedback:</p1><br>
<textarea rows="5" cols="50" name="feedback"><?php echo $text;?></textarea><br><br>
<input type="submit" Value="Send Feedback"><br><br>
<?php
error_reporting(E_ALL);
$name = $_POST['fullname'];
$email = $_POST['email'];
$feed = $_POST['feedback'];
if (empty($name))
{
echo "Please enter your name, email and feedback.";
}
if (empty($email))
{
echo "Please enter your email and feedback.";
}
if (empty($feed))
{
echo "Please enter feedback.";
}
if (!empty($name) && !empty($email) && !empty($feed))
{
echo "You have inserted the correct data";
}
?>
</form>
</body>
</html>
However, when I run it on Chrome, I got a server error 500 saying that
The website encountered and error while retrieving process_4.php. It maybe down for maintenance or configured incorrectly.
The other PHP files that I've made leading up to this point have all worked correctly and I don't know why this one isn't.

Related

How to not redirect and display the error if the user enter invalid input

I'm new to PHP and I just want to make some form like a basic form. But I have trouble in the values entered by the user. For example if they enter a empty field it should not redirect or if in the email they didn't enter a correct format the form should not redirect. But in my case it always redirect even though the input is invalid. Can you help me out on how can I stop redirecting to another page if the value entered by the user is invalid?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FG4</title>
</head>
<style>
.error {color: red}
</style>
<body>
<?php
$fname = $lname = $fgender = $mail = $dob = $address = "";
$fnameErr = $lnameErr = $genderErr = $mailErr = $dobErr = $addressErr = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if (empty($_GET["fname"])) {
$fnameErr = "Please enter your first name.";
} else {
$fname = input($_GET["fname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$fname)) {
$fnameErr = "Please enter a valid name";
}
}
if (empty($_GET["lname"])) {
$lnameErr = "Please enter your last name.";
} else {
$lname = input($_GET["lname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$lname)) {
$lnameErr = "Please enter a valid name";
}
}
if (empty($_GET["gender"])) {
$genderErr = "Please select a gender.";
} else{
$gender = input($_GET["gender"]);
}
if (empty($_GET["mail"])) {
$mailErr = "Please enter your email.";
} else {
$mail = input($_GET["mail"]);
// check if email contain gmail.com or yahoo.com
if (!preg_match("/#gmail.com|#yahoo.com/", $mail)) {
$mailErr = "Please enter a valid email.";
}
}
if (empty($_GET["dob"])) {
$dobErr = "Please select your date of birth.";
} else{
$lname = input($_GET["lname"]);
}
if (empty($_GET["address"])) {
$addressErr = "Please enter your address.";
} else {
$address = input($_GET["address"]);
// check if address contain the following characters
if (!preg_match(" /#|[0-9]|[a-z]|[A-Z]/ ",$address)) {
$address = "Please enter a valid address";
}
}
}
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="get" action="trial.php">
First Name: <input type="text" name="fname">
<span class="error">* <?php echo $fnameErr;?></span>
<br><br>
Larst Name: <input type="text" name="lname">
<span class="error">* <?php echo $lnameErr;?></span>
<br><br>
Gender: <input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Email: <input type="text" name="mail">
<span class="error">* <?php echo $mailErr;?></span>
<br><br>
Date of Birth: <input type="date" name="dob">
<span class="error">* <?php echo $dobErr;?></span>
<br><br>
Address: <br><textarea type="text" name="address" rows="5" cols="40"></textarea>
<span class="error"><?php echo $addressErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Here is the other code where it just print the values entered by the user
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// collect value of input field
$fname = $_GET['fname'];
$lname = $_GET['lname'];
$gender = $_GET['gender'];
$mail = $_GET['mail'];
$dob = $_GET['dob'];
$address = $_GET['address'];
echo "<h2> Final Output:</h2>";
echo "First Name :$fname";
echo "<br>";
echo "Last Name :$lname";
echo "<br>";
echo "Gender :$gender";
echo "<br>";
echo "Email :$mail";
echo "<br>";
echo "Date of Birth :$dob";
echo "<br>";
echo "Address :$address";
}
?>
</body>
</html>
There are many ways to do what you want.
One of them is to use a hidden form and submit it only if there is no error found after the validation.
Hence the amended code (based on your original code) will be:
trial.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FG4</title>
</head>
<style>
.error {color: red}
</style>
<body>
<?php
$fname = $lname = $fgender = $mail = $dob = $address = "";
$fnameErr = $lnameErr = $genderErr = $mailErr = $dobErr = $addressErr = "";
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if (empty($_GET["fname"])) {
$fnameErr = "Please enter your first name.";
} else {
$fname = input($_GET["fname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$fname)) {
$fnameErr = "Please enter a valid name";
}
}
if (empty($_GET["lname"])) {
$lnameErr = "Please enter your last name.";
} else {
$lname = input($_GET["lname"]);
// check if name only contains letters and space
if (!preg_match("/^[a-zA-Z-' ]*$/",$lname)) {
$lnameErr = "Please enter a valid name";
}
}
if (empty($_GET["gender"])) {
$genderErr = "Please select a gender.";
} else{
$gender = input($_GET["gender"]);
}
if (empty($_GET["mail"])) {
$mailErr = "Please enter your email.";
} else {
$mail = input($_GET["mail"]);
// check if email contain gmail.com or yahoo.com
if (!preg_match("/#gmail.com|#yahoo.com/", $mail)) {
$mailErr = "Please enter a valid email (only #gmail.com or #yahoo.com).";
}
}
if (empty($_GET["dob"])) {
$dobErr = "Please select your date of birth.";
} else{
$lname = input($_GET["lname"]);
}
if (empty($_GET["address"])) {
$addressErr = "Please enter your address.";
} else {
$address = input($_GET["address"]);
// check if address contain the following characters
if (!preg_match(" /#|[0-9]|[a-z]|[A-Z]/ ",$address)) {
$address = "Please enter a valid address";
}
}
}
function input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form id="form_id" method="get" action=#>
First Name: <input type="text" name="fname" value="<?php echo $_GET["fname"];?>">
<span class="error">* <?php echo $fnameErr;?></span>
<br><br>
Larst Name: <input type="text" name="lname" value="<?php echo $_GET["lname"];?>">
<span class="error">* <?php echo $lnameErr;?></span>
<br><br>
Gender: <input type="radio" name="gender" value="male"
<?php if ($_GET["gender"]=="male") { echo " checked ";} ?>
> Male
<input type="radio" name="gender" value="female"
<?php if ($_GET["gender"]=="female") { echo " checked ";} ?>
> Female
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Email: <input type="text" name="mail" value="<?php echo $_GET["mail"];?>">
<span class="error">* <?php echo $mailErr;?></span>
<br><br>
Date of Birth: <input type="date" name="dob" value="<?php echo $_GET["dob"];?>">
<span class="error">* <?php echo $dobErr;?></span>
<br><br>
Address: <br><textarea type="text" name="address" rows="5" cols="40"><?php echo $_GET["address"];?></textarea>
<span class="error"><?php echo $addressErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if ($fnameErr=="" && $lnameErr=="" && $genderErr=="" && $mailErr=="" && $dobErr=="" && $addressErr=="") { ?>
<form id="form_id2" method=GET action="trial2.php">
<input type=hidden name="fname" value="<?php echo $_GET["fname"];?>">
<input type=hidden name="lname" value="<?php echo $_GET["lname"];?>">
<input type=hidden name="gender" value="<?php echo $_GET["gender"];?>">
<input type=hidden name="mail" value="<?php echo $_GET["mail"];?>">
<input type=hidden name="dob" value="<?php echo $_GET["dob"];?>">
<textarea name=address style="display:none;"><?php echo $_GET["address"];?></textarea>
</form>
<script>
document.getElementById("form_id2").submit();
</script>
<?php } ?>
trial2.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// collect value of input field
$fname = $_GET['fname'];
$lname = $_GET['lname'];
$gender = $_GET['gender'];
$mail = $_GET['mail'];
$dob = $_GET['dob'];
$address = $_GET['address'];
echo "<h2> Final Output:</h2>";
echo "First Name :$fname";
echo "<br>";
echo "Last Name :$lname";
echo "<br>";
echo "Gender :$gender";
echo "<br>";
echo "Email :$mail";
echo "<br>";
echo "Date of Birth :$dob";
echo "<br>";
echo "Address :$address";
}
?>
</body>
</html>

How to send email to user input email address after click a submit button? In php

I'm super new at coding. This is the form page code
<?php
// Start the session
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$fnameErr = $emailErr = $addressErr = $countryErr = $stateErr = $suburbErr = "";
$fname = $email = $address = $country = $state = $suburb = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "Name is required";
} else {
$fname = test_input($_POST["fname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["address"])) {
$addressErr = "Address is required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["country"])) {
$countryErr = "City is required";
} else {
$country = test_input($_POST["country"]);
}
if (empty($_POST["state"])) {
$stateErr = "State is required";
} else {
$state = test_input($_POST["state"]);
}
if (empty($_POST["suburb"])) {
$suburbErr = "State is required";
} else {
$suburb = test_input($_POST["suburb"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2 align="cemter">Check out</h2>
<p><span class="error">* required field</span></p>
Full Name: <input type="name" name="fname">
<span class="error">* <?php echo $fnameErr;?></span>
<br><br>
E-mail: <input type="email" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Address: <input type="text" name="address">
<span class="error">*<?php echo $addressErr;?></span>
<br><br>
Country: <input type="text" name="country">
<span class="error">*<?php echo $countryErr;?></span>
<br><br>
State: <input type="text" name="state">
<span class="error">*<?php echo $stateErr;?></span>
<br><br>
Suburb: <input type="text" name="suburb">
<span class="error">*<?php echo $suburbErr;?></span>
<br><br>
<form method="post" action="../mailer/index.php">
<input type="submit" name="submit" value="Purchase">
</form>
</body>
</html>
But after I fill up all the information and click submit, the page said cannot connect to SMTP sever host. The strange thing is, I can send email while run the phpmailer index.php alone. The form page php file and the mailer php file is in a different folder but same parent folder, is this the problem?
If one page works and another doesn't, and these are in different folders, then yes, that could be the problem. However, the solution is probably not to just move one of the files (which would probably give you other path related issues), but instead make sure that they both can reach the neccessary configuration (SMTP server host in this case).

how to make form validation working when submitting to another page

Validation doesn't work on my form
I want validation to run in my form and show errors
here's my code for Contact Form.php
<p><span class="error"> * required field(s)</span></p>
<form action="user_input.php" method="post">
<table>
<tr>
<td><label>Name: <span class="error"> *<?php echo $nameErr;?> </span></label></td></tr>
<td><input name="name" type="text" placeholder="Type your name" value="<?php echo $name;?>"></td>
<tr><td><label>Email: <span class="error"> *<?php echo $emailErr;?> </span></label></td></tr>
<td><input name="email" type="email" placeholder="Type your email" value="<?php echo $email;?>"></td>
<tr><td><label>Address: <span class="optional"> Optional</span></label></td></tr>
<td><input name="address" type="text" placeholder="Type your location" value="<?php echo $address;?>"></td>
<tr><td><label>Phone: <span class="error"> * <?php echo $phoneErr;?></span></label></td></tr>
<td><input name="phone" type="tel" placeholder="Type your phone number" value="<?php echo $phone;?>"></td>
<tr><td><label>Message: <span class="error"> * <?php echo $messageErr;?> </span></label></td></tr>
<td><textarea name="message" row="5" cols="40" placeholder="Type your message here" value="<?php echo $message;?>"></textarea></td>
</table>
<input type="submit" value="Submit">
and my code for user_input.php
<?php
$nameErr = $emailErr = $addressErr = $phoneErr = $messageErr = "";
$name = $email = $address = $phone = $message = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["name"])) {
$nameErr = "Name required";
header("location: contact_form.php");
} else {
$name = input($_POST["name"]);
}
if(empty($_POST["email"])) {
$emailErr = "Email required";
header("location: contact_form.php");
} else {
$email = input($_POST["email"]);
// check if email is valid
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email";
header("location: contact_form.php");
}
}
if(empty($_POST["address"])) {
$addressErr = "Invalid Address";
header("location: contact_form.php");
} else {
$address = input($_POST["address"]);
}
if(empty($_POST["phone"])) {
$phoneErr = "Phone number required";
header("location: contact_form.php");
} else {
$phone = input($_POST["phone"]);
if(!preg_match("/^[0-9]+$/", $phone) || strlen($phone) > 20) {
$phoneErr = "Invalid phone number";
header("location: contact_form.php");
}
}
if (empty($_POST["message"])) {
$messageErr = "Message required";
header("location: contact_form.php");
} else {
$message = input($_POST["message"]);
}
}
I don't know where I have errors it should be able to output errors and validating.
I want only php not jquery or javascript
You should store the error messages in a session.
What you do now is setting a variable that is limited to the runtime. As soon as the user changes the page (what he does with location header) they will be flushed. Sessions are not flushed and can be used on per user basis and will be viable for 30 minutes default I think (config can change the duration)
Just add errors like
session_start();
$_SESSION['errors'][] = 'Name required';
On the page you can now access them like foreach($_SESSION['errors'] as $error){... and then delete them unset($_SESSION['errors']);
Remove header() function from error condition and also use an array for storing your errors. instead of multiple variables.

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>

Validating email before sending it from validated PHP form

I'm using this code from W3 (http://www.w3schools.com/php/php_form_complete.asp) to make server side validation for given example form.
<!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 syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
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>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Although server side validation works fine,I can't put mail() function to work ONLY WHEN both $name (treated as subject) and $comment (treated as message) fields are filled.
I've tried many combinations but email is always submitted even when fields are empty.
So my question is: how to make this validated form send email only when $name and $comment fields are filled and validated?
As you are creating $nameErr when the name is invalid and $comment is an empty string when the comment is valid you can use the following conditional:
if (!$nameErr && $comment) {
}
Empty strings are considered FALSE:
http://php.net/manual/en/language.types.boolean.php
You can always use flags.
<?php
....
// let's say there are some flags for validation
if($flag1 && $flag2 && .. $flagN){
// perform email sending here
}
?>
Or you can use the default error message variables; check if they are empty
<?php
if(!empty($nameErr) && !empty($comment)){
// perform email sending
}
?>
Do the validation after you validated $name and $comment:
if($nameErr == "" && $emailErr == "") { // If they are empty, no errors where found
// Do your email validation here
}

Categories