I have created a form as follows but now I need to validate user input using PHP. As a security measure you should not only rely on javascript/ HTML 5 form
validation to validate your form submissions. You should always employ server
side validation to verify any data that is being submitted
Write PHP code that will do the following:
1. Validate that firstName, lastName and email are required
2. Validate that age if entered is a number
3. validate the email and website entries to ensure they are valid
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<?php
$firstName="";
$lastName="";
$email="";
$age="";
$website="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$firstName = "First name is required";
}
else {
$firstName = test_input($_POST["firstName"]);
}
if (empty($_POST["lastName"])) {
$lastName = "Last name is required";
}
else {
$lastName = test_input($_POST["lastName"]);
}
if (empty($_POST["email"])) {
$email = "Email is required";
}
else {
$email = test_input($_POST["email"]);
}
if (is_numeric ($_POST["age"])) {}
else { $age ="Age must be numeric";
}
}
echo $firstName;
echo $lastName;
echo $email;
echo $age;
?>
<form action="." method="POST">
<input type="text" name="firstName" placeholder="*First Name" /><br>
<input type="text" name="lastName" placeholder="*Last Name" /><br>
<input type="text" name="email" placeholder="*Email" /><br>
<input type="text" name="age" placeholder="Age" /><br>
<input type="text" "name="website" placeholder="Website" /><br>
<input type="submit" name="submit" value="Submit" />
</form>
<body>
</body>
</html>
So that it looks like this:
try this
Hint store them in array then display them
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$error['firstName'] = "First name is required";
}
else {
$firstName = test_input($_POST["firstName"]);
}
if (empty($_POST["lastName"])) {
$error['lastName'] = "Last name is required";
}
else {
$lastName = test_input($_POST["lastName"]);
}
if (empty($_POST["email"])) {
$error['email'] = "Email is required";
}
else {
$email = test_input($_POST["email"]);
}
if (is_numeric ($_POST["age"])) {
}
else { $error['age'] ="Age must be numeric";
}
}
?>
<html>
<body>
<form action="" method="POST">
<?php echo $error['firstName'] = "First name is required".'<br/>';?>
<input type="text" name="firstName" placeholder="*First Name" /><br>
<?php echo $error['lastName'] = "First name is required".'<br/>';?>
<input type="text" name="lastName" placeholder="*Last Name" /><br>
<?php echo $error['email'].'<br/>'?>
<input type="text" name="email" placeholder="*Email" /><br>
<?php echo $error['age'].'<br/>'?>
<input type="text" name="age" placeholder="Age" /><br>
<input type="text" "name="website" placeholder="Website" /><br>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Here, this is a form that I happen to have in my scripts library, and you can modify it to suit your needs.
Strangely enough, it has a function called test_input() and will do what you wanted to achieve.
Sidenote: Be sure to change this to your own $myemail = "email#example.com";
<?php
ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<style>
.error {color: #FF0000;}
h6
{
font-family: bookman old style;
font-size:20px;
text-align: center;
font-weight: normal;
}
h5
{
font-family: bookman old style;
font-size:15px;
text-align: center;
font-weight: normal;
}
</style>
<?php
$nameErr = $emailErr = $websiteErr = $commentErr = $categoryErr = "";
$name = $email = $comment = $website = $category = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$Err = 1;
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$Err = 1;
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$Err = 1;
// die();
}
}
if (empty($_POST["website"])) {
$websiteErr = "URL is required";
$Err = 1;
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
// $comment = "";
$commentErr = "Comment is required";
$Err = 1;
} else {
$comment = test_input($_POST["comment"]);
}
// if (empty($_POST["category"])) {
if ($_POST["category"] == "" ) {
$categoryErr = "Category is required";
$Err = 1;
} else {
$category = test_input($_POST["category"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<h6>Link Submission</h6>
<h5><span class="error">* required field.</span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name Of Site: <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>
URL: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error">* <?php echo $websiteErr;?></span>
<br><br>
Description: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea><span class="error">* <br><?php echo $commentErr;?></span>
<br><br>
Category Of Site: <select size="1" name="category">
<option value="<?php echo $category;?>"> -- Please select -- </option>
<option>Arts</option>
<option>Business</option>
<option>Computers</option>
<option>Games</option>
<option>Health</option>
<option>Home</option>
<option>Kids and Teens</option>
<option>News</option>
<option>Recreation</option>
<option>Reference</option>
<option>Science</option>
<option>Shopping</option>
<option>Society</option>
<option>Sports</option>
<option>World</option>
</select><span class="error">* <?php echo $categoryErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</h5>
<?php
if(isset($_POST['submit'])){
if ($Err != 1){
$myemail = "email#example.com";
$subject = "Link Submission";
$message = "Your Link Submission form has been submitted by:
Website Name: $name
E-mail: $email
URL: $website
Category: $category
Description:
$comment";
$headers = "From: ". $name . " <" . $email . ">\r\n";
mail($myemail, $subject, $message, $headers);
// header('Location: submit_thanks.php');
echo "OK";
}
}
?>
I think you can try using PHP_SELF. A simple example:
HTML
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method='POST'>
<input type='submit' name='submit'/>
</form>
PHP
<?php
if (isset($_POST['submit'])) {
echo "your code here";
}
?>
Related
Please check my code. I have to 2 fields for validate email
one is
if ($email == NULL) {
$error['email'] = "email is missing";
}
another is
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
But my Problem is when email field is blank/empty. I found those 2 warring is show. "email is missing" & "email is Invalid"; I want only one warring will show. Such as if email filed is blank/empty. It will show only "email is missing" not show me "email is Invalid" and when email is not valid It will show "email is Invalid". Below is my full code.
<?php
if (isset($_POST['contact'])) {
$warning = array();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$msg = $_POST['message'];
$to = "asifurrahaman124#gmail.com";
$sub = "you got a msg";
$headers = "from: $email";
if ($firstname == NULL) {
$error['fname'] = "firstname is missing";
}
if($lastname == NULL){
$error['lname'] = "Last name is missing";
}
if ($email == NULL) {
$error['email'] = "email is missing";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
if ($msg == NULL) {
$error['msg'] = "message is required";
}
if (count( $error ) == 0) {
mail($to, $sub, $msg, $headers);
$success = "Message Submited";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>conatact</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form action="" method="POST">
<input type="text" name="firstname" Placeholder="First Name"><br />
<p class="error"><?php if (isset($error['fname'])) {
echo $error['fname'];
}?></p>
<input type="text" name="lastname" Placeholder="Last Name"><br />
<p class="error"><?php if (isset($error['lname'])) {
echo $error['lname'];
}?></p>
<input type="email" name="email" Placeholder="Email"><br />
<p class="error"><?php if (isset($error['email'])) {
echo $error['email'];
}?></p>
<p class="error"><?php if (isset($error['emailfilter'])) {
echo $error['emailfilter'];
}?></p>
<textarea name="message" cols="30" rows="10"></textarea><br />
<p class="error"><?php if (isset($error['msg'])) {
echo $error['msg'];
}?></p>
<input type="password" name="password" Placeholder="Password"><br />
<input type="submit" value="send" name="contact">
</form>
<h2 class="error"><?php if (isset($success)) {
echo $success;
}?></h2>
</body>
</html>
You want to use elseif for this, it will only trigger if the first condition isn't matched.
if ($email == NULL) {
$error['email'] = "email is missing";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['emailfilter'] = "email is Invalid";
}
This will check the first condition, do they have an email, if not it'll populate $error['email'], if the email has a value then it'll perform the filter_var on the email to check it's validity.
Before I get into it I would like to say that this did send emails from my local server so I have everything set up. After adding this form validation it no longer sends emails or shows errors. It just refreshes the page. I'm new to php coding so I'm sure I just have an if statement in the wrong order or something like that.
HTML
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
PHP
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = localhost;
$EmailTo = "testrepairmail69#gmail.com";
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Your Code is begging for some improvements as #R Smith mentioned; nevertheless this version works; i have tested on my pc.
<?php
$firstname_error = $lastname_error = $email_error = $message_error = "";
$firstname = $lastname = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstname_error = "First name is required";
} else {
$firstname = test_input($_POST["firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
$firstname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["lastname"])) {
$lastname_error = "Last name is required";
} else {
$lastname = test_input($_POST["lastname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
$lastname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
// var_dump($_POST); exit();
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$EmailFrom = "test#gamil.com";
$EmailTo = "tabletscreenfixer.com";//-> the message will be sent to this address if you have configure mail stuff well
$Subject = "New Order From tabletscreenfixer.com";
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}else{
echo "Failure";
}
}else{
echo "Failure 2";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<head>
<title>Test</title>
</head>
<body>
<section id="contact">
<h1 class="section-header">Contact Us Directly</h1>
<h4 class="text-center">Have any quesitons not answered in the <span>Questions Page</span>.</h4>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" value="<?php echo $firstname ?>" placeholder="Your name.." tabindex="1" autofocus>
<span class="error"><?php echo $firstname_error ?></span>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" value="<?php echo $lastname ?>" placeholder="Your last name.." tabindex="2">
<span class="error"><?php echo $lastname_error ?></span>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="<?php echo $email ?>" placeholder="Your email.." tabindex="3">
<span class="error"><?php echo $email_error ?></span>
<label for="message">Message</label>
<textarea id="subject" name="message" value="<?php echo $message ?>" placeholder="Write something.." style="height:200px" tabindex="4"> </textarea>
<span class="error"><?php echo $message_error ?></span>
<input type="submit" value="Submit" tabindex="5">
<span class="success"><?php $success ?></span>
</form>
</section>
</body>
</html>
EDIT: Missing echo in the input value attribute;
Hope it helps;
Add some debugging. For example, everywhere you have an error, increment a error counter. Something like this:
if (empty($_POST["email"])) {
$email_error = "Email is required";
$errors++;
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
Then, at the end, instead of the long if condition:
if ($firstname_error == '' and $lastname_error == '' and $email_error == '' and $message_error == '' ){
You can use something like:
if ($errors == 0){
Which indicates no errors. Then, inside that if, when you try to send the mail, check for failure:
if (mail($EmailTo, $Subject, $message)){
$success = "Message sent, thank you for contacting us!";
$firstname = $lastname = $email = $message = '';
}
else {
echo "The mail command failed!!";
}
Finally, give yourself some sort of indicator that there were errors, just for your testing phase. You can remove this else (or even add better styling and keep it):
if ($errors == 0){
// snip - lines of code in here removed to keep this snippet readable. this is your test and send mail logic.
}
else {
echo "You've got $errors errors! You need to correct them!";
}
With these changes, you should be able to find your issues quickly. As I said, you can also remove some of this code (like the echo statements) once you've finished your debugging.
Good luck!
I have to validate a form and send an email..I copied this form from w3schools and attached mailto function.But i dont know how to display "Thank you for submitting" After the form is processed. Kindly Help.. The Thank you message should display on the same page below Submit Button.
Here is my code..
<!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";
}
}
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
$to = "dheeraj.narayan1712#gmail.com";
$subject = "My subject";
$name = "Name: $name";
$email = "$email";
$headers = "From: webmaster#example.com" . "\r\n" .
"CC: somebodyelse#example.com";
mail($to,$subject,$name,$headers);
?>
</body>
</html>
It's rather simple;
if(isset($email)){
echo 'Success! Thanks for submitting';
}
And then just place it after the mail function? Notice that you can change $email to any of the POST variables that you want, and also change the echo'ed content. (if you want to place it inside of the form remember to wrap it in
<?php ?>
I am making a PHP form and not sure how to go about having the code say "message delivered" when clicking submission and having it validate correctly. Here is my code so far. I realize that the message appears anytime you click submit. Thank you for your patience.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $comment = $message = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
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["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (isset($_POST["submit"])) {
$message = "Message has been delivered";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="cntr">
<h2>Contact Form</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div class="field">
<label for="name">Name </label>
<br>
<input type="text" name="name">
<span class="error">*<?php echo $nameErr;?></span>
</div>
<div class="field">
<label for="email">Email</label>
<br>
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
</div>
<div class="field">
<label for="message">Message</label>
<br>
<textarea name="comment" rows="8" cols="40"></textarea>
</div>
<button type="submit" class="email" name="submit" value="Submit">Submit</button>
<?php echo $message; ?><br/>
</form>
</div>
Use
if (isset($_POST["submit"]) && empty($nameErr) && empty($genderErr) && empty($emailErr) && empty($websiteErr)) {
$message = "Message has been delivered";
}
instead of
if (isset($_POST["submit"])) {
$message = "Message has been delivered";
}
Because isset($_POST["submit"]) is true when ever you do a submit , so you need to check the error variables are empty also . if the error variables are empty that means your code validated and passed .
I have this code I put together from other scripts and stuff I found on the internet,
Somehow it is sending me two emails, one email when I just load the page, the second of course when I submit.
Also, the header() is not sending me to the page I want it to...it just stays on the same form page, if anyone can help me find out what is going on, it would be much appreciated, I think it does have something to do with the post to self, but I can not for the love of me figure it out!
Thank you
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<style>
.error {color: #FF0000;}
h6
{
font-family: bookman old style;
font-size:20px;
text-align: center;
font-weight: normal;
}
h5
{
font-family: bookman old style;
font-size:15px;
text-align: center;
font-weight: normal;
}
</style>
<?php
$nameErr = $emailErr = $websiteErr = $categoryErr = "";
$name = $email = $comment = $website = $category = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
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"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$websiteErr = "URL is required";
} else {
$website = test_input($_POST["website"]);
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["category"])) {
$categoryErr = "Category is required";
} else {
$category = test_input($_POST["category"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<?php include'header.php'?>
<h6>Link Submission</h6>
<h5><span class="error">* required field.</span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name Of Site: <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>
URL: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error">* <?php echo $websiteErr;?></span>
<br><br>
Description: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Category Of Site: <select size="1" name="category">
<option value="<?php echo $category;?>"> -- Please select -- </option>
<option>Arts</option>
<option>Business</option>
<option>Computers</option>
<option>Games</option>
<option>Health</option>
<option>Home</option>
<option>Kids and Teens</option>
<option>News</option>
<option>Recreation</option>
<option>Reference</option>
<option>Science</option>
<option>Shopping</option>
<option>Society</option>
<option>Sports</option>
<option>World</option>
</select><span class="error">* <?php echo $categoryErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</h5><?php include'footer.php'?>
<?php
$myemail = "links#loadsofads.com";
$subject = "Link Submission";
$message = "Your Link Submission form has been submitted by:
Website Name: $name
E-mail: $email
URL: $website
Category: $category
Description:
$comment";
mail($myemail, $subject, $message);
header('Location: submitthanks.php');
?>
It's sending you two emails because you need to set your entire code inside a conditional statement.
Use isset() in conjunction with your already named submit button, which will only send mail once the submit button has been clicked and not on page load.
<input type="submit" name="submit" value="Submit">
Modify to:
<?php
if(isset($_POST['submit'])){
$myemail = "links#loadsofads.com";
$subject = "Link Submission";
$message = "Your Link Submission form has been submitted by:
Website Name: $name
E-mail: $email
URL: $website
Category: $category
Description:
$comment";
mail($myemail, $subject, $message);
header('Location: submitthanks.php');
exit;
}
In regards to the header not redirecting is because you are outputting before header, which if error reporting had been set/on, would throw a Headers already sent... warning.
Adding ob_start(); at the top of your page and set inside <?php ?> tags sometimes help, and placed above <!DOCTYPE html...
I.e.:
<?php ob_start(); ?>
<!DOCTYPE html ...
You would be better off using an form action to another page instead of on the same page, and putting your mail codes in that file.
Another option would be to use a meta refresh method instead, if you wish to use your present code and not use a second page as the mail handler.
For example and in place of header():
$url = "submitthanks.php";
print "<meta HTTP-EQUIV=Refresh CONTENT=\"0; URL=$url\">";
Edit: - rewrite #2
Be sure to change this line $myemail = "email#example.com"; to be your Email address.
Plus, there was a mail() header missing which would most likely send mail to Spam,
and added a from Name so it's more personalized.
<?php
ob_start(); // prevents headers already sent warning
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<style>
.error {color: #FF0000;}
h6
{
font-family: bookman old style;
font-size:20px;
text-align: center;
font-weight: normal;
}
h5
{
font-family: bookman old style;
font-size:15px;
text-align: center;
font-weight: normal;
}
</style>
<?php
$nameErr = $emailErr = $websiteErr = $commentErr = $categoryErr = "";
$name = $email = $comment = $website = $category = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
$Error = 1;
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$Error = 1;
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
$Error = 1;
}
}
if (empty($_POST["website"])) {
$websiteErr = "URL is required";
$Error = 1;
} else {
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
$Error = 1;
} else {
$comment = test_input($_POST["comment"]);
}
if ($_POST["category"] == "" ) {
$categoryErr = "Category is required";
$Error = 1;
} else {
$category = test_input($_POST["category"]);
}
} // brace for if ($_SERVER["REQUEST_METHOD"] == "POST")
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<?php include 'header.php'; ?>
<h6>Link Submission</h6>
<h5><span class="error">* required field.</span>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name Of Site: <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>
URL: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error">* <?php echo $websiteErr;?></span>
<br><br>
Description: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea><span class="error">* <br><?php echo $commentErr;?></span>
<br><br>
Category Of Site: <select size="1" name="category">
<option value="<?php echo $category;?>"> -- Please select -- </option>
<option>Arts</option>
<option>Business</option>
<option>Computers</option>
<option>Games</option>
<option>Health</option>
<option>Home</option>
<option>Kids and Teens</option>
<option>News</option>
<option>Recreation</option>
<option>Reference</option>
<option>Science</option>
<option>Shopping</option>
<option>Society</option>
<option>Sports</option>
<option>World</option>
</select><span class="error">* <?php echo $categoryErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</h5><?php include 'footer.php'; ?>
<?php
if(isset($_POST['submit'])){
if ($Error != 1){
$myemail = "email#example.com";
$subject = "Link Submission";
$message = "Your Link Submission form has been submitted by:
Website Name: $name
E-mail: $email
URL: $website
Category: $category
Description:
$comment";
$headers = "From: ". $name . " <" . $email . ">\r\n";
mail($myemail, $subject, $message, $headers);
header('Location: submitthanks.php');
} // brace for if ($Error != 1)
} // brace for if(isset($_POST['submit']))
?>
you need to put this part of your code in the post section
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$myemail = "links#loadsofads.com";
$subject = "Link Submission";
$message = "Your Link Submission form has been submitted by:
Website Name: $name
E-mail: $email
URL: $website
Category: $category
Description:
$comment";
mail($myemail, $subject, $message);
header('Location: submitthanks.php');