I'm having troubles validating my form. How do I validate the form using PHP? I've tried lots of different methods and nothing has worked. I can get the inputs to display (although check-box doesn't always display) but it just won't validate.
I also want to display the user's inputs (after it has been validated) onto another page, how do I do that?
Here is my code;
Form:
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="" required>
<br><br>
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" value="" required>
<br>
<br>
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" value="" required>
<br>
<br>
Recipient:
<div>
<label for="admin">
<input type="checkbox" name="recipient[]" id="admin" value="Administrator">
Administrator</label>
<br>
<label for="editor">
<input type="checkbox" name="recipient[]" id="editor" value="Content Editor">
Content Editor</label>
<br>
</div>
<br>
<label for="message">Message:</label>
<br>
<textarea name="message" id="message" cols="45" rows="5" required></textarea>
<input type="hidden" name="submitted" value="1">
<br>
<input type="submit" name="button" id="button" value="Send">
<br>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($_POST['submitted']==1) {
if ($_POST['name']){
$name = $_POST['name'];
}
else{
echo "<p>Please enter a name.</p>" ;
}
if (preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email))
$email = $_POST['email'];
}
else{
echo "<p>Please enter a valid email.</p>";
}
if ($_POST['subject']){
$subject = $_POST['subject'];
}
else{
echo "<p>Please enter a subject.</p>";
if(empty($_POST['recipient'])){
echo "<p>Please select a recipient</p>";
}else{
for ($i=0; $i < count($_POST['recipient']);$i++) {
echo $_POST['recipient'][$i] . " ";
}
}
}
if ($_POST['message']){
$message = $_POST['message'];
}
/* go to form.php
display results
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong> ";
echo "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
*/
?>
if (preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)#[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,3})$/i", $email)
You can't use email in this condition because $email is empty!
Related
Update:
I've added echo $errors to the end of my code. Now I am getting that all fields are required although all are filled:
} else {
echo $errors;
}
I've created a simple php e-mail form with this example (link). And jQuery form validator (link).
Now what I get after submiting a form is just a empty "contact-form-handler.php" page.
You can see the form live at: mantasmilka.com/#contactPage
What could be the problem? Below is my code.
contact-form-handler.php
<?php
$errors = '';
$myemail = 'mantas#mantasmilka.com';//<-----Put Your email address here.
if(empty($_POST['infoname']) ||
empty($_POST['infocompany']) ||
empty($_POST['infoemail']) ||
empty($_POST['infophone']) ||
empty($_POST['infodescription'])
)
{
$errors .= "\n Error: all fields are required";
}
$jobtype = $_POST['jobtype'];
$budget = $_POST['budget'];
$location = $_POST['location'];
$infoname = $_POST['infoname'];
$infocompany = $_POST['infocompany'];
$infoemail = $_POST['infoemail'];
$infophone = $_POST['infophone'];
if (isset($_POST['infodescription'])) {
$infodescription = $_POST['infodescription'];
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$infoemail))
{
$errors .= "\n Error: Invalid email address";
}
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Jobtype: $jobtype \n Budget: $budget \n Location: $location \n Name: $infoname \n Company: $infocompany \n E-mail: $infoemail \n Phone: $infophone \n ".
"Message \n $infodescription";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $infoemail";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
// header('Location: http://www.mantasmilka.com/index.php');
header('Location: index.php');
exit();
} else {
echo $errors;
}
?>
my form in index.php:
<form id="contactform" method="post" name="contact_form" action="contact-form-handler.php">
<div class="left">
<fieldset class="jobtype">
<legend>Job type</legend>
<input type="radio" name="jobtype" id="project" value="project" required>
<label for="project">Project</label>
<input type="radio" name="jobtype" id="part-time" value="part-time" >
<label for="part-time">Part-time</label>
<input type="radio" name="jobtype" id="full-time" value="full-time" >
<label for="full-time">Full-time</label>
</fieldset>
<fieldset class="budget">
<legend>Budget</legend>
<input type="radio" name="budget" id="budget5k" value="budget5k" required>
<label for="budget5k">5k € ></label>
<input type="radio" name="budget" id="budget10k" value="budget10k" >
<label for="budget10k">5k - 10k €</label>
<input type="radio" name="budget" id="budget15k" value="budget15k" >
<label for="budget15k">15k € <</label>
</fieldset>
<fieldset class="location">
<legend>Location</legend>
<input type="radio" name="location" id="locremote" value="locremote" required>
<label for="locremote">Remote</label>
<input type="radio" name="location" id="loclocal" value="loclocal" >
<label for="loclocal">Local with relocation</label>
</fieldset>
</div>
<div class="right">
<fieldset class="contactinfo">
<legend>Your Contact Info</legend>
<div class="input-holder">
<input type="text" name="infoname" id="infoname" value="" required data-validation="alphanumeric">
<label for="infoname">Name</label>
</div>
<div class="input-holder">
<input type="text" name="infocompany" id="infocompany" value="" required data-validation="alphanumeric">
<label for="infocompany">Company</label>
</div>
<div class="input-holder">
<input type="text" name="infoemail" id="infoemail" value="" required data-validation="email">
<label for="infoemail">E-mail</label>
</div>
<div class="input-holder">
<input type="text" name="infophone" id="infophone" value="" required data-validation="number">
<label for="infophone">Phone</label>
</div>
<div class="input-holder textarea">
<textarea name="infodescription" form="contact_form" rows="4" required></textarea>
<label for="infodescription">Message</label>
</div>
<div class="input-holder submit">
<input type="submit" name="submit" value="Submit" required/>
</div>
</fieldset>
</div>
</form>
text field should look like this don't put form tag in here
<textarea name="infodescription" rows="4" required></textarea>
in php make the if statement like this the first ( opens the if statement the last ) closes it and take not of how i used the other brackets
if(
(empty($_POST['infoname'])) ||
(empty($_POST['infocompany'])) ||
(empty($_POST['infoemail'])) ||
(empty($_POST['infophone'])) ||
(empty($_POST['infodescription']))
)
{
$errors .= "\n Error: all fields are required";
}
The efficient way to solve the problem is:
$('#contactform').submit(function(ev) {
ev.preventDefault();
if($('#infodescription').val() == '')
{
alert('Description is required');
return false;
}
//add other validation
this.submit(); // If all the validations succeeded
});
By this you can avoid the unwanted server load.
I'm trying to get a contact form working, and I'm being redirected to the PHP file itself, and I'm not sure why. I'm fairly new to PHP and I'm not entirely sure what I'm doing wrong. I'd love to be pointed in the right direction. The code is below.
Thanks
HTML:
<p id='feedback'><?php echo $feedback; ?></p>
<form id="contact_us" enctype="text/plain" method="post" action="form.php">
<input class="form_field" type="text" name="Name" placeholder="Full Name">
<br>
<input class="form_field" type="text" name="Company" placeholder="Company Name">
<br>
<input class="form_field" type="email" name="Email_Address" placeholder="Email Address">
<br>
<textarea class="form_field" rows="10" cols="20" name="Description" wrap="hard" placeholder="Project Description"></textarea>
<br>
<p id="required"><i>Please fill in all the fields*</i></p>
<input class="submit" type="submit" value="SUBMIT">
</form>
PHP:
<?php
$to = 'zack#zfisch.com';
$subject ='Dropset Work Request';
$name = $_POST['Name'];
$company = $_POST['Company'];
$email = $_POST['Email_Address'];
$message = $_POST['Description'];
$message = <<<EMAIL
From: $name
$message
Email: $email
EMAIL;
$header = $subject;
if($_POST) {
mail($to, $subject, $message, $header);
$feedback = 'Email sent!';
}
?>
This line tells the form what PHP file to send the data to:
<form id="contact_us" enctype="text/plain" method="post" action="form.php">
In particular, it is this part that sends the data to a particular form:
action="form.php"
In fact, this is fine. You can process a form in the same PHP file that contains the form. Just put the PHP form processing at the top:
<?php
if (isset($_POST['Email_Address'] && $_POST['Email_Address'] != ''){
$to = 'zack#zfisch.com';
$subject ='Dropset Work Request';
$name = $_POST['Name'];
$company = $_POST['Company'];
$email = $_POST['Email_Address'];
$message = $_POST['Description'];
$message = <<<EMAIL
From: $name
$message
Email: $email
EMAIL;
$header = $subject;
if($_POST) {
mail($to, $subject, $message, $header);
$feedback = 'Email sent!';
}
}else{
>?
<p id='feedback'><?php echo $feedback; ?></p>
<form id="contact_us" enctype="text/plain" method="post" action="form.php">
<input class="form_field" type="text" name="Name" placeholder="Full Name">
<br>
<input class="form_field" type="text" name="Company" placeholder="Company Name">
<br>
<input class="form_field" type="email" name="Email_Address" placeholder="Email Address">
<br>
<textarea class="form_field" rows="10" cols="20" name="Description" wrap="hard" placeholder="Project Description"></textarea>
<br>
<p id="required"><i>Please fill in all the fields*</i></p>
<input class="submit" type="submit" value="SUBMIT">
</form>
<?php
}
?>
Just remove enctype="text/plain" otherwise your code is correct in HTML and try to echo feedback variable other way is to write all your code above the HTML like below:
<?php
if (isset($_POST['Email_Address'] && !empty['Email_Address']){
$to = 'zack#zfisch.com';
$subject ='Dropset Work Request';
$name = $_POST['Name'];
$company = $_POST['Company'];
$email = $_POST['Email_Address'];
$message = $_POST['Description'];
$message = <<<EMAIL
From: $name
$message
Email: $email
$header = $subject;
if($_POST) {
mail($to, $subject, $message, $header);
$feedback = 'Email sent!';
}
}else{
>?
<p id='feedback'><?php echo $feedback; ?></p>
<form id="contact_us" enctype="text/plain" method="post" action="form.php">
<input class="form_field" type="text" name="Name" placeholder="Full Name">
<br>
<input class="form_field" type="text" name="Company" placeholder="Company Name">
<br>
<input class="form_field" type="email" name="Email_Address" placeholder="Email Address">
<br>
<textarea class="form_field" rows="10" cols="20" name="Description" wrap="hard" placeholder="Project Description"></textarea>
<br>
<p id="required"><i>Please fill in all the fields*</i></p>
<input class="submit" type="submit" value="SUBMIT">
</form>
<?php
}
?>
Im using this php script to send the contents of my form to my email when the user submits the form, but currently im only able to get the last two fields of my form to send in the email.( message and company name are the only two working) How can I get the entire form to send in the email?
<form role="form" method='post' action='backend/php_mailer.php'>
<input type="text" name='name' class="form-control" id="yourname" placeholder="Name">
<input type="email" name='email' class="form-control" id="email" placeholder="Email">
<input type="text" name='phone' class="form-control" id="phone" placeholder="Phone">
<input type="text" name='company' class="form-control" id="company" placeholder="Company Name">
<textarea name='message' class="form-control" id="message" rows="6" placeholder="Message"></textarea>
<button type="submit" class="btn btn-primary btn-lg ">SUBMIT</button>
</form>
<?php
if (isset($_POST['email']))
{
$userName = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$phone = $_REQUEST['phone'] ;
$company = $_REQUEST['company'] ;
$message = $_REQUEST['message'] ;
mail("peaceuponelove#gmail.com", $subject,
$message,$company,$userName );
echo "Thank you";
}
?>
Each argument of mail() has a specific purpose. You cannot just continually pass in arguments and expect them to be appended to the email. You must use string concatenation.
$message = $_REQUEST['message'] . '</br>' . $email . '<br/>' . $phone . '<br/> ' . $userName . '<br/> . ' $company;
mail("peaceuponelove#gmail.com", $subject,$message);
Sidenote You never declared $subject in the code that you've shown. So here's a subject:
$subject = 'Message from '. $userName .' < ' . $email . ' > ';
Here is what i ended up doing to get all fields in email
<?php
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<input name="name" type="text" value="" size="30"/><br>
<input name="email" type="text" value="" size="30"/><br>
<input name="phone" type="text" value="" size="30"/><br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$phone=$_REQUEST['phone'];
$message=$_REQUEST['message'].$email.$phone;
$subject="$name";
mail("peaceuponelove#gmail.com", $subject, $message);
echo "Email sent!";
?>
Here's my code:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yourname"])) {
$yournameErr = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
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["message"])) {
$messageErr = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I have got to the point where it doesn't show errors but I probably didn't explain myself too clearly. After the point at which it doesn't show error messages anymore, I would like the form to no longer appear and then I can put something down like "Successful." However I can't seem to achieve this.
my form is :
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br />
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1; border-color:#000000; " />
<span class="error">* <?php echo $yournameErr;?></span>
</div>
<br />
<br />
<div>
<label> Email :</label> <br />
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1; border-color:#000000; " />
<span class="error">* <?php echo $emailErr;?></span>
</div>
<br />
<br />
<div>
<label> Subject : </label><br />
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1; border-color:#000000; " />
</div>
<br />
<br />
<div>
<label> Message :<br /> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message"
placeholder="The message you want to send to us." style="border:1; border-
color:#000000 " >
</textarea>
<span class="error">* <?php echo $messageErr;?></span>
</div>
<br />
<br />
<div>
<input type="submit" name="button" id="button" style="border:1; border-
color:#999999; " value="SEND"/>
</div>
</form>
What if you put your errors in an array and put a condition that check that array size and if it is 0 (no errors) echo the success message and don't show the form else join the errors and print it out.
Maybe like this:
contact.php
<?php
$error = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yourname"])) {
$error['name'] = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
if (empty($_POST["email"])) {
$error['email'] = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$error['email'] = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$error['message'] = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if (!count($error)) {
$noError = true;
}
}
$successMessage = isset($noError) ? 'Successful.' : '';
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function getErrorMessage($type, $error)
{
return isset($error[$type]) ? $error[$type] : '';
}
if ($successMessage) {
echo $successMessage;
} else {
?>
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br/>
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1px; border-color:#000000; "/>
<span class="error">* <?php echo getErrorMessage('name', $error); ?></span>
</div>
<br/>
<br/>
<div>
<label> Email :</label> <br/>
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1px; border-color:#000000; "/>
<span class="error">* <?php echo getErrorMessage('email', $error); ?></span>
</div>
<br/>
<br/>
<div>
<label> Subject : </label><br/>
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1px; border-color:#000000; "/>
</div>
<br/>
<br/>
<div>
<label> Message :<br/> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message"
placeholder="The message you want to send to us." style="border:1px; border-
color:#000000 "></textarea>
<span class="error">* <?php echo getErrorMessage('message', $error); ?></span>
</div>
<br/>
<br/>
<div>
<input type="submit" name="button" id="button" style="border:1px; border-
color:#999999; " value="SEND"/>
</div>
</form>
<?php } ?>
According to your code, I'm going to assume that your contact.php is posting to itself. In other words, your PHP code is located above your HTML --as a result of your question that the contact form no longer renders after a request. That is, once the server renders the page, the form tag will not display because there are no errors in the submission or the super global $_POST has been set.
I've slightly altered your code for readability. I included an array that will hold all your error messages throughout your form validation. If there are no errors, then we can simulate a successful submission and thus reflect this result on response. Your form will only display if there are errors OR the post has not been submitted.
Inside your form, you need an input tag of submit. Furthermore, only if errors are indeed set, that we want to display an error specific message. That is why a condition is set for your span tags. Lastly, I included the same condition in your values -an additional feature for remembering what you have entered.
If the form is successfully submitted, then don't render the form tag and, instead, display a message of success along with all the POST data!
<?php
if (isset($_POST['submit'])) {
$error_message = array();
if (empty($_POST["yourname"])) {
$error_message['yournameErr'] = "Name is required";
} else {
$yourname = test_input($_POST["yourname"]);
}
if (empty($_POST["email"])) {
$error_message['emailErr'] = "Email is required";
} elseif (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $_POST["email"])) {
$error_message['emailErr'] = "Invalid email format";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["message"])) {
$error_message['messageErr'] = "Message is required";
} else {
$message = test_input($_POST["message"]);
}
if(empty($error_message)) {
// process data from post
$successful = true;
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php if(!empty($error_message) || !isset($_POST['submit'])) : ?>
<form action="contact.php" name="Form1" id="Form1" method="post">
<div>
<label>Your Name:</label>
<br />
<input type="text" name="yourname" id="yourname" placeholder="Full Name"
style="border:1; border-color:#000000; " value="<?php if(isset($yourname)) {echo $yourname; }?>" />
<span class="error">* <?php if(isset($error_message['yournameErr'])){echo $error_message['yournameErr']; }?></span>
</div>
<br />
<br />
<div>
<label> Email :</label> <br />
<input name="email" type="text" id="email" size="20" placeholder="Email"
style="border:1; border-color:#000000; " value="<?php if(isset($email)) { echo $email;}?>" />
<span class="error">* <?php if(isset($error_message['emailErr'])) {echo $error_message['emailErr'];}?></span>
</div>
<br />
<br />
<div>
<label> Subject : </label><br />
<input name="subject" type="text" id="subject" size="20" placeholder="Subject"
style="border:1; border-color:#000000; " />
</div>
<br />
<br />
<div>
<label> Message :<br /> </label>
<textarea rows="5" cols="40" name="message" type="text" id="message" placeholder="The message you want to send to us." style="border:1; border-color:#000000"></textarea>
<span class="error">* <?php if(isset($error_message['messageErr'])) {echo $error_message['messageErr']; }?></span>
<br>
<input type="submit" name="submit" value="Submit">
</div>
<?php endif; ?>
<?php if(isset($successful)) : ?>
<p>Successful</p>
<p>Your name: <?=$yourname;?></p>
<p>Your email: <?=$email;?></p>
<p>Your subject: <?=$_POST['subject']?></p>
<p>Your message: <?=$message;?></p>
Back to form
<?php endif; ?>
I have set up a PHP mail form set up that only correctly outputs some of the variables entered in the form. It DOES mail the $name and $email variables, but not the $message variable.
The php to send the form is here:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST" ){
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$message = trim($_POST["message"]);
//sending email
require_once("siteIncludes/class.phpmailer.php");
$mail = new PHPMailer();
$email_body = "";
$email_body = $email_body . "Name: " . $name . $message . "<br />";
$email_body = $email_body . "Email: " . $email . "<br />";
$email_body = $email_body . "Message: " . $message;
$mail->SetFrom("$email,$name");
$address = "foo#bar.com";
$mail->AddAddress($address);
$mail->Subject = "Form Submission | ".$name;
$mail->MsgHTML($email_body);
if(!$mail->Send() ){
echo 'There was a problem sending the email: '.$mail->ErrorInfo;
exit();
}
header("Location: myContact.php?status=thanks");
exit();
};
?>
And the HTML that sets up the form is here:
<div id="contactFormWrap" class="span6 offset3">
<form method="post" action="myContact.php" id="contactForm">
<div>
<label for="name">Please leave your name</label>
<input type="text" name="name" id="name" value="" class="required" />
</div>
<div>
<label for="email">and your email</label>
<input type="text" name="email" id="email" value="" class="required email" />
</div>
<div>
<label for="subject">What is your message about?</label>
<input type="text" name="subject" id="subject" value="" class="required" />
</div> -->
<div>
<label for="message">and your message</label>
<textarea name="message" id="message" value="" rows="10" class="required"></textarea>
</div>
<div id="messageButtons">
<input type="submit" value="Submit" name="contactSubmit" id="contactSubmit" class="sendEmail btn" />
</div>
</form>
</div>
I hope that was enough information. Does anyone know why the $message variable isn't being output to the submitted email?
thanks
I think this is your problem:
value=""
The <textarea> tag does not have a value attribute, however different browsers have different ways of handling invalid code, so whatever browser you are using must be using the value found in this invalid attribute instead of what you type in the actual text box.
Just do:
<textarea name="message" id="message" rows="10" class="required"></textarea>