how to set validation in contact form - php

how to set validation in contact from
suppose if user submit empty field then how to show Invalid input
now email address only invalid input show i want to fix all field validation please help me how can i do this
thanks in advance
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<h2>Form</h2>
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="email"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback">
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["email"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["email"]);
if ($mailcheck==FALSE) {
echo "Invalid input";
} else {
$email = $_POST["email"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("demo#gmail.com",$subject,$message,"From: $email\n");
echo "Thank you for sending us feedback";
}
}
}
?>
</body>
</html>

Use these
From: <input type="email" name="email" required><br>
Subject: <input type="text" name="subject" required><br>
Message: <textarea rows="10" cols="40" name="message" required></textarea><br>
Refer this and this

Related

How can i set Dynamic Header in mail using codeigniter ?

I want to set a Dynamic Header on mail header when i send mail. I don't want to do it with SMPT server and if it will be in codeigniter, so it will be greate. You will get idea what exactly i want by given image bellow.
from: Google < dynamic email#gmail.com >
My Code
<?php
if(isset($_POST['send'])) {
//Email information
$email = $_POST['email'];
$subject = $_POST['subject'];
$comment = $_POST['comment'];
//send email
mail($email, "$subject", $comment, "From:" . $email);
//Email response
echo "Thank you for contacting us!";
}
//if "email" variable is not filled out, display the form
else {
?>
<form method="post" name="testmail">
Email: <input name="email" type="text" />
Subject: <input name="subject" type="text" />
Message:<textarea name="comment" rows="15" cols="40"></textarea>
<input type="submit" name="send" value="Submit" />
</form>
<?php } ?>
use like this:
mail(to,subject,message,headers,parameters);

Email validation using PHP

I have a form for which i am trying to validate the email address. If the email address is incorrect i want a value of "Please type a valid email address." to be returned into the "email" input box on the form. What am i doing wrong? No validation is taking place. I receive the form information at my email and once submitted the user is sent to the "Thank you" page, but no validation. I can put anything in the "email" input and the form will submit.
<form action="../php/contact.php" method="post">
<p>First Name:</p>
<input class="box_style" type="text" name="first_name" required maxlength="20" />
<p>Last Name:</p>
<input class="box_style" type="text" name="last_name" required maxlength="25" />
<p>Email:</p>
<input class="box_style" type="text" name="email" required maxlength="50" />
<p>Contact Number (optional):</p>
<input class="box_style" type="text" name="contact_number" maxlength="12" />
<p>How did you find us?</p>
<select class="box_style" name="how" required>
<option value="choose">Select...</option>
<option value="referal">Referal</option>
<option value="website">Website</option>
<option value="search">Search Engine</option>
<option value="card">Business Card</option>
</select>
<p>Enquiries:</p>
<textarea class="box_style" name="inquiries" cols="30" rows="10"></textarea>
<input class="box_style" type="submit" name="submit" value="Submit"/>
</form>
and this is the php
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$fName = $lName = $email = $cNum = $how = $enquiries = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = test_input($_POST["first_name"]);
$lName = test_input($_POST["last_name"]);
$cNum = test_input($_POST["contact_number"]);
$how = test_input($_POST["how"]);
$enquiries = test_input($_POST["enquiries"]);
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
}};
$email_from = 'my#email.com';
$email_subject = "New Inquiry";
$email_body = "You have received a new message from" ." ". "$fName" ." ". "$lName" ."\n".
"$inquiries"."\n".
"Referal Type:" ." ". "$how" ."\n".
"Contact Number:" ." ". "$cNum" ."\n";
$to = "my#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to,$email_subject,$email_body,$headers);
?>
Thank You
Here's a simplified version of the OP's code that demonstrates how to display the error message by having the action attribute of the form be the same url as that which displays the form. The code also exemplifies some nice touches for the user:
<?php
include("php4myform.php");
?>
<html>
<head>
<title>Email Validate</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<label for="email">Email: </label>
<input id="email" name="email" required maxlength="50" value="<?php echo $e_mess; ?>">
<input type="submit" name="submit" value="Submit">
<input type="reset" id="clear" value="clear">
</form>
<script src="myJS4forms.js"></script>
</body>
</html>
php4myform.php:
<?php
$e_mess = "";
if ( isset($_POST['submit']) && $_POST != null) {
$tainted_email = trim($_POST["email"]);
$sanitized_email = filter_var($tainted_email, FILTER_SANITIZE_EMAIL);
if( !filter_var( $sanitized_email, FILTER_VALIDATE_EMAIL ) ) {
$e_mess = "Please type a valid email address.";
}
else
{
// Data is good to go.
}
}
myJS4forms.js:
var d = document;
d.g = d.getElementById;
var email = d.g("email");
var reset = d.g("clear");
function selFoc(obj){
obj.focus();
obj.select();
}
window.onload = function() {
selFoc( email );
};
reset.addEventListener("click",function(e) {
e.preventDefault();
email.value=null;
selFoc( email );
});
A few notes:
The drawback of testing with $_SERVER["REQUEST_METHOD"] is that the user might submit an empty form. Therefore, the PHP code in this example tests to see if the form was submitted and if the POST contains any data.
It is ill-advised to use htmlspecialchars() with filter_var and the parameter FILTER_EMAIL_SANITIZE; see this discussion and here, too. The code employs htmlspecialchars() instead to safeguard $_SERVER['PHP_SELF'] -- basis: this article.
I removed stripslashes() since magic quotes are deprecated and gone as of PHP5.4; see the online Manual. (Using addslashes() to escape data is inadvisable -- better to use mysqli_real_escape_string().) Also, filter_var with FILTER_SANITIZE_EMAIL will remove any slashes (see Manual).
If you redirect the user using a "header()" function, you need to stop the execution of the script. So the correct way would be something like this:
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
exit();
}
If you don't terminate the script, it will continue executing the rest of the file.
Secondly, if you print something to the user and immediately redirect him elsewhere, he will never see the message. If you want to do a redirection and show the message there, you need to store the message first, probably in a session variable, and then show it on the "landing page".

Include fields in message of PHP contact form

Being so bad at PHP, I've decided to post here as a last resort.
I want to add a "who" variable to the message body of emails sent via PHP contact form. The form works fine for name, email and message but the "who" input I would like to be a part of the email message that comes through, as a way to communicate who is being referred.
I have tried to add $who=$_REQUEST['who']; as well as $who to the mail line but neither work, the latter doesn't even send an email at all.
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
<input name="name" type="text" placeholder="Your Name" value="" size="14"/>
<input name="email" type="text" placeholder="Your Email" value="" size="14"/>
<textarea name="who" placeholder="Who should we contact?" rows="1" cols="14"></textarea>
<textarea name="message" placeholder="Description" rows="2" cols="14"></textarea><br>
<input type="submit" class="button special" value="SUBMIT"/>
</form>
<?php
}
else
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "All fields are required, please fill out the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Referral for ******* **";
mail("chris#********.com.au", $subject, $message, $from);
}
{
echo "<script type='text/javascript'>window.location.href ='../thanks.php';</script>";
}
}
?>
In PHP . is the concatenation operator which returns the concatenation of its right and left arguments
Try this
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'] . "\n\rFrom: " . $_REQUEST['who'];

How can I show the PHP results of a contact form with AJAX?

I have a simple html contact form, and the php script to send the emails. It's working good, but I want the result (The email has been sent...) to show in the same page, without changing the page. How can I do this?
HTML:
<form name="contact" action="includes/send.php" id="contact_form">
<input type="text" placeholder="Name" name="name" /> <br />
<input type="email" placeholder="Email Address" name="email" /> <br />
<textarea name="message" placeholder="Message" rows="8"></textarea> <br />
<input type="submit" name="submit" id="submit_btn" value="Send" />
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'amar123syla#gmail.com';
$subject = 'Message from AMARSYLA.COM';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: amar123syla#gmail.com';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message) or die('Error sending Mail'); //This method sends the mail.
echo "Your email was sent!"; // success message
}
?>
jQuery.post('email.php', score, function(result) {
jQuery('#textBlock').html(result);
});
Something like that should work(Result is the echo in your php in this case)
A preffered method is to encode your php result to json so you've got a little more control over it in Javascript though.
jQuery.post('email.php', score, function(result) {
if (result.result == true) {
jQuery('#textBlock').html(result.text);
}
});
And in the email.php:
$result['result'] = true;
$result['text'] = 'Message has been sent';
header('Content-Type: application/json');
echo json_encode($result);
Here see if this works:
<form name="contact" action="**submit to same page**" id="contact_form">
<input type="submit" name="submit" id="submit_btn" value="Send" />
</form>
Then for the php (on the same page as the email form) just add if submit
<?php
if(isset($_POST['submit'])){
run your email script, add javascript, etc.
echo "Your email was sent!"; // success message
}
}
?>

PHP form takes back to top

I have PHP included a PHP form in my portfolio, that you can see here http://www.tinybigstudio.com The thing is that after SUBMIT, the page goes to TOP instead of staying at the bottom where the form is.
This is the PHP code I have:
<?php
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#tinybigstudio.com'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' .$subject = "You have mail, yes!" . "\r\n" . 'Te lo manda: ' . $name;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
And this is the form:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">
<fieldset>
<label for="name">Name</label>
<input type="text" size="50" name="contactname" id="contactname" value="" class="required">
<label for="email">Email</label>
<input type="text" size="50" name="email" id="email" value="" class="required">
<label for="message">Message</label>
<textarea rows="5" cols="50" name="message" id="message" class="required"></textarea>
<input type="submit" value="S E N D" class="send" name="submit" onmouseover="this.className='send_hover';"
onmouseout="this.className='send';">
</form>
<?php if(isset($hasError)) { //If errors are found ?>
<p class="error">Please check if you've filled all the fields with valid information. Thank you.</p>
<?php } ?>
<?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
<p><strong>Message Successfully Sent!</strong></p>
<p>Thank you <strong><?php echo $name;?></strong> for sending a message!</p>
<?php }
?>
you need to add an anchor to the contact form and use this as the form action.eg:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>#contact" >
and add this 'pseudo-link' right before the contact form
<a name="contact">Contact me</a>
Now after submit user will be send to the form directly and not the top of the page
This is because you are submitting it to the same page that you are on, therefore the browser goes effectively refreshes with the $_POST data. If you want to stop this you need to use AJAX to submit it so that it happens in the background. Take a look at the API - http://api.jquery.com/jQuery.ajax/

Categories