I have got the following form to work using PHP and JavaScript to validate...
The problem is, each time I want to update the inputs in the form I need to also update the && isset and $input = $_REQUEST['input name']; in the PHP! Are these important? there is no way to make the whole process easier?! please advise
PHP:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
ob_start();
if(isset($_REQUEST['name'])
&& isset($_REQUEST['email'])
&& isset($_REQUEST['message'])
&& isset($_REQUEST['number'])
&& isset($_REQUEST['date'])
&& isset($_REQUEST['select'])
&& isset($_REQUEST['radio'])
&& isset($_REQUEST['checkbox'])
&& isset($_REQUEST['token'])){
if($_SESSION['token'] != $_POST['token']){
$response = "0";
} else {
$_SESSION['token'] = "";
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$number = $_REQUEST['number'];
$date = $_REQUEST['date'];
$select = $_REQUEST['select'];
$radio = $_REQUEST['radio'];
$checkbox = $_REQUEST['checkbox'];
$to = "";
$subject = "New Message From: $name";
$message = "Name: $name<br/>
number: $number<br/>
date: $date<br/>
select: $select<br/>
radio: $radio<br/>
checkbox: $checkbox<br/>
Email: $email<br/>
Message: $message";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: '.$email . "\r\n";
$mailed = (mail($to, $subject, $message, $headers));
if( isset($_REQUEST['ajax']))$response = ($mailed) ? "1" :
"0"; else $response = ($mailed) ? "<h2>Success!</h2>" :
"<h2>Error! There was a problem with sending.</h2>";
echo $response;
}
} else {
echo "Form data error!";
}
ob_flush();
die();
}
?>
HTML Form:
<?php
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
?>
<!--Contact Form-->
<form id="contactForm" name="contactForm" action="contact.php" method="post">
<input name="token" type="hidden" value="<?php echo $token; ?>">
<input name="ajax" type="hidden" value="1">
<div class="name">
<p>Your Name</p>
<input name="name" class="required" autocomplete="off">
</div>
<div class="email-address">
<p>Email Address</p>
<input name="email" class="required email" autocomplete="off">
</div>
<div class="message">
<p>Message</p>
<textarea name="message" rows="5" class="required min3"></textarea>
</div>
<div class="number">
<p>Phone Number</p>
<input name="number" class="number" autocomplete="off">
</div>
<div class="date">
<p>Date <small>(dd/mm/yyyy)</small></p>
<input name="date" class="required date calendar" autocomplete="off">
</div>
<div class="dropdown">
<select name="select" class="required">
<option value="">Select</option>
<option value="DropdownA">DropdownA</option>
<option value="DropdownB">DropdownB</option>
</select>
</div>
<div class="radio">
<p>Radios:</p>
<label><input name="radio" type="radio" value="male" class="required">Male</label>
<label><input name="radio" type="radio" value="female" class="required">Female</label>
</div>
<div class="checkbox">
<p>Checkboxs:</p>
<label><input name="checkbox" type="checkbox" value="OptionA" class="required">Option A</label>
<label><input name="checkbox" type="checkbox" value="OptionB" class="required">Option B</label>
</div>
<div>
<p></p>
<input name="" class="required number spamcheck">
</div>
<button id="submit" type="submit">Send</button>
</form>
You do need to check if variables are set, before using them. Otherwise your script will raise errors for undefined variables. E.g. You each time will try to check if $_SESSION['token'] != $_POST['token'] but it will give you errors, because there's no form submitted (or however the request is sent) with token name, that's why you do need to check it before that.
Anyway, for multiple isset() you can use a comma separator
if(isset($var, $var2, $var3...))
instead of
if(isset($var) && isset($var2)...))
Also,, if you session token is not initialized too (completely new request to the page), and no request is send to it, your if() statement will return false, thus triggering the mail() function. So, in you particular case it's more than necessary to have a check before using them in mail form.
Yes. They are important. Lots of ways to make the process easier though. You might want to look at a simple framework like Symfony (the forms component can be used independently of the whole framework).
Be aware that you'll probably get a massive amount of spam with that form. Add a captcha like reCaptcha.
Yes, the validation is important but you can simplify your code. I would use an array to define the required fields. It's easy to maintain and much less code.
$requiredFields = array('name', 'email', 'message', 'number');
$valid = true;
foreach ($requiredFields as $field) {
if (!isset($_REQUEST[$field])) {
$valid = false;
break;
}
}
if ($valid) {
// Do the stuff
} else {
echo "Form data error!";
}
If you want to check if the current field actually contains something add empty() to the condition:
if (!isset($_REQUEST[$field]) || empty($_REQUEST[$field])) {
I think the second part where you assign the post values to separate variables is actually unnecessary in this case.
Related
I cant think anymore, stuck trying to make this work. I've got two radio buttons, how do I send the form to one of two email adresses depending on the button clicked. I am a total idiot on php, thank you.
html
<div class="col-md-8 contact-top">
<h3>Book here Online!</h3>
<form method="post" action="FormtoEmail/FormtoEmail.php">
<form role="form">
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Name">
</div> <div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="subject" class="form-control" id="subject" placeholder="Subject">
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1">Booking Accommodation</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2" >Booking Conference</label>
</div>
<div class="form-group">
<textarea rows="11" name="message" id="message" class="form-control" placeholder="Details"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
my php
<?php
$my_email = "info#westcoastwebdesign.biz";
$continue = "/";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Check all fields for an email header.
function recursive_array_check_header($element_value)
{
global $set;
if(!is_array($element_value)){if(preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i",$element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_header($value);}
}
}
recursive_array_check_header($_REQUEST);
if($set){$errors[] = "You cannot send an email header";}
unset($set);
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
if(preg_match("/(%0A|%0D|\n+|\r+|:)/i",$_REQUEST['email'])){$errors[] = "Email address may not contain a new line or a colon";}
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 || stristr($_REQUEST['email']," ")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("#",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."";
$message = stripslashes($message);
$subject = "Out of Africa Town Lodge Contact Form";
$headers = "From: " . $_POST['email'];
$recipients = array(
'recipient_1' => 'info#westcoastwebdesign.biz',
'recipient_2' => 'westcoastwebdesign77#gmail.com'
);
$my_email = $recipients[$_REQUEST['recipient']];
mail($my_email,$subject,$message,$headers);
?>
You need to use a radio button group with same name but value with different email id
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_1#email.com">
Booking Accommodation
</label>
</div>
<div class="radio">
<label><input type="radio" name="recipients" value="recipient_2#email.com" >
Booking Conference
</label>
</div>
That way you can select one from two radio
in FormtoEmail.php
//use post to get the email id
$to = $_POST['recipients'];
and send mail using PHPMailer, its great library and will make your life easier
May you want use this code:
<?php
if(isset($_POST['recipients']) && $_POST['recipients'] == 'recipient_1') {
// send to recipient_1
} else {
// send to recipient_2
}
?>
$my_email = $recipients[$_REQUEST['recipient']];
There is a typo in $_REQUEST variable, it would be $recipients[$_REQUEST['recipients']];
Hope it will work now. It could be more easily done in anyway.
i am working on one page ajax contactform . I want to send an email with PHP without leaving my page and now i'm completely lost. I have no idea why its not working
i'll show you my contact form. thank you for help in advance. Here is the form ..
html code
<article class="panel" style="background:url(img/cover/bg_panel_3.jpg); background-size:cover;" full-screen>
<div style="padding-top:80px;">
<div class="row text-center centered">
<div id="contact-form">
<form id="contact-us" action="contact.php" method="post">
<ul>
<li class="field" id="check-1">
<input class="input txt requiredField wide alpha-only" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" placeholder="Name" onBlur="check(this.value)" />
</li>
<li class="field" id="check-2">
<input class="input wide mail-only txt requiredField email" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" placeholder="Email" />
</li>
<li class="field" id="check-3">
<input class="input wide hack-check sub-check requiredField" name="subj" type="text" placeholder="Subject" value="<?php if(isset($_POST['subj'])) echo $_POST['subj'];?>" />
</li>
<li class="field" id="check-4">
<input class="input wide num-only requiredField" name="num" type="text" placeholder="Number" value="<?php if(isset($_POST['num'])) echo $_POST['num'];?>" />
</li>
<li class="field" id="check-5">
<textarea class="input textarea wide hack-check msg-check txtarea requiredField" name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:">
<?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?>
</textarea>
</li>
</ul>
<div class="medium primary btn pretty-btn">
<input name="submit" class="subbutton" type="submit" value="Send" />
</div>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
<!-- End #contact -->
</div>
</div>
</div>
</article>
**js code **
$(document).ready(function() {
$('form#contact-us').submit(function() {
$('form#contact-us .error').remove();
var hasError = false;
});
if(!hasError) {
var formInput = $(this).serialize();
alert(formInput);
$.post("contact-us.php",formInput, function(data){
$('form#contact-us').slideUp("fast", function() {
$(this).before('<p class="tick fg-white sans"><strong>Thanks!</strong> Your email has been delivered. !</p>' );
});
});
}
return false;
});
});
PHP Code
//If the form is submitted
if(isset($_POST['submitted'])) {
$name = trim($_POST['contactName']);
$email = trim($_POST['email']);
$num = trim($_POST['num']);
$subject = trim($_POST['subj']);
$comments = trim($_POST['comments']);
$formcontent=" From : $name \n Email : $email \n Subject : $subj \n Phone number : $number \n \n Message : $message";
$recipient = "example#mail.com";
$subject = "Contact Form Query Received";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error encountered! Please try again or write directly to the mentioned email address.");
// set our boolean completion value to TRUE
$emailSent = true;
}
I suspect your problem is this extra }); in your code which is stopping the $.post(...) call from even being called. A quick lint of your JS shows this up, as does careful reading.
var hasError = false;
======> }); <====== remove this extra stuff.
if(!hasError) {
I'm trying to create a page for my website, where students have to select 3 or less out of about 10 choices(multiple selection). They also need to upload a file below this. When they click submit finally, it would send the file they uploaded to multiple email addresses (or even a specific single email address would work)based on their selection (3 or less out of 10 choices).
Can someone please help me out? I have a okay knowledge of HTML, but I don't know JavaScript and hence I'm having a lot of trouble figuring it out. I have looked up various posts on the internet, but I couldn't find something that was pretty similar and worked.
Also, I am using WordPress, and since I need to add Javascript to the page, I installed a plugin called Exec-PHP Plugin. It seems like it works, however please do let me know your opinion.
Thanks so much, really appreciate any help!
EDIT: This is the code I tried. Its what I found when I looked through various posts. Its not exactly what I mentioned in this question, since like I mentioned before I do not have any previous knowledge of JavaScript. Here, its basically supposed to send a message to the email based on a single drop-down selection. I tried it, but it did not work (I changed the destination emails).
Thanks!
<form id="contactForm" method="post" accept-charset="utf-8">
<input id="name" type="text" name="name" minlength="2" placeholder="Your Name…" required>
<input id="email" type="email" name="email" placeholder="Your Email…" required>
<input id="name2" type="text" name="name2" placeholder="Your Last Name…" required>
<select id="department" type="text" name="department">
<option value="customer" name="customer">I am a customer</option>
<option value="distribution" name="distribution">department in distribution</option>
<option value="press" name="press">I am with the press</option>
<option value="career" name="career">department in a career position</option>
<option value="other" name="other">Other</option>
</select>
<textarea name="message" placeholder="Your Message…" required></textarea>
<input type="submit" value="Send away!">
</form>
<?php
// We use the name2 field as bait for spambots. It's display is off,
// so humans wouldn't know to enter anything into it. Robots would,
// so we ignore submissions with info in name2.
$mail_sent = false;
if(sizeof($_POST) && $_POST["name2"] == "") // receiving a submission
{
define("SUBJECT", "Visitor Message from Website");
// production recipient:
define("RECIPIENT", ".$department.");
// prep our data from the form info
$senderName = $_POST['name'];
$senderEmail = $_POST['email'];
$department = $_POST['department'];
$subject = SUBJECT;
$messageBody = $senderName . ' ('.$senderEmail.') wrote in '.$department.':
' . $_POST['message'];
if($department == 'customer') { //if customer was selected
$to = 'customer#gmail.com';
}
else if($department == 'distribution') { //if distribution was selected
$to = 'distribution#email.com';
}
else if($department == 'press') { //if press was selected
$to = 'press#email.com';
}
else if($department == 'career') { //if career was selected
$to = 'career#email.com';
}
else if($department == 'other') { //if other was selected
$to = 'other#email.com';
}
// From
$header = "from: $senderName <$senderEmail>";
// To
$to = RECIPIENT;
// Send it!
$send_contact = mail($to, $subject, $messageBody, $header);
// Check success of send attempt
if($send_contact){
// show thankyou screen
$mail_sent = true;
}
else {
// send failed.
echo "ERROR";
}
}
?>
I dont have a sample code to give you, but roughly, it would be something like this:
<html>
<head>
<script type="text/javascript">
function my_js_submit()
{
// check the email input fields that you care about.
if(document.getElementById("email1").value != "" &&
document.getElementById("email2").value != "" &&
document.getElementById("email3").value != "")
{
document.forms["my_form"].submit(); //this will call the php where you do
//emailing
}
else
{
alert("Please fill in all three emails");
}
}
</script>
</head>
<body>
<!-- submit_handler.php is where you send emails -->
<form id="my_form: method="post" action="submit_handler.php">
<input type="text" id="email1" />
<input type="text" id="email2" />
<input type="text" id="email3" />
<input type="text" id="message" />
<button onclick="my_js_submit();"> Submit </button>
</form>
</body>
</html>
PHP most basic code (name this file submit_handler.php):
<?php
$to = $_POST['email1'] . "; " . $_POST['email2'] . "; " . $_POST['email3'];
$subject = "Email subject";
$message = $_POST['message'];
$from = "From: your_email#yourDomain.com";
mail($to,$subject,$message,$from); // The Mail function at work
// Redirect your user to a page of your choice
header("Location: http://www.some_page.com");
?>
I have a form in html whose "action" attribute calls a contact.php file. The problem is that after I submit the form, the file that is visible is a blank page with the address contact.php and I want to see again the form of the main page.
HTML:
<form id="myForm" action="php-contact/contact.php"
method="post" class="contact_form" autocomplete="off"
role="form">
<div class="form-group">
<label for="input-subject">subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="your subject" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-name">name</label>
<input name="name" type="text" class="form-control" id="name" placeholder="your name" maxlength="20"/>
</div>
<div class="form-group">
<label for="input-email">email address</label>
<input name="email" type="text" class="form-control" id="email" placeholder="your email" maxlength="40"/>
</div>
<div class="form-group" >
<label for="input-message">message</label>
<textarea name="message" cols="10" rows="10" class="form-control" id="comment" ></textarea>
</div>
<button name="myFormSubmitted" type="submit" class="btn btn-primary btn-lg btn-block">send</button>
</form>
PHP:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "pep.g#gmail.com";
$message = '
name: '.$name.'
email: '.$email.'
message: '.$message.'
';
$headers = 'From: pep.website#website.com';
if (
mail($to, $subject, $message, $headers)
)
echo"<script>alert('message send succesfully')</script>";
else
echo"<script>alert('message not send')</script>";
?>
Use either $_SERVER["HTTP_REFERER"] or use a hidden field on the form with the url of the current page:
<form action="myAction.php">
<input type="hidden" name="destination" value="<?php echo $_SERVER["REQUEST_URI"]; ?>"/>
<!-- other form inputs -->
<input type="submit"/>
</form>
myAction.php
<?php
/* Do work */
if(isset($_REQUEST["destination"])){
header("Location: {$_REQUEST["destination"]}");
}else if(isset($_SERVER["HTTP_REFERER"])){
header("Location: {$_SERVER["HTTP_REFERER"]}");
}else{
/* some fallback, maybe redirect to index.php */
}
And then even then you should have fallbacks in case for some reason the client isn't respecting HTTP redirects, like some redirect javascript, a meta redirect and a link to the destination.
Add a JS redirect after your alert then
echo "<script>
alert('message sent succesfully');
window.history.go(-1);
</script>";
In your contact.php file, just use something like at the end of the PHP code:
header("location:yourfilenamehere.php");
This will redirect back to whatever page you specify.
You could do two things...
1) Have your php logic in the form file and submit to that file. On the top of the file, put something like:
if(isset($_POST['name'])) {
// your sending logic
}
followed by your form.
2) use the header() function to redirect to your form.
header("Location: form.html");
I feel pretty bad about posting this answer as it is just concatenating two other SO answers.
First part
Charlie74's answer on this page
// add the message you want to show to the user
header("Location: yourfilenamehere.php?alertmsg=message+send+succesfully");
exit();
Second part check for the alertmsg name in the query string
See SO post for getParameterByName:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
in the page you are redirecting call the getParameterByName function:
<script>
var msg = getParameterByName('alertmsg');
if (alertmsg.length > 0) {
alert(msg);
}
</script>
html code:
Contact Me
<label for="Name">Name:</label>
<input type="text" name="name" id="Name" accesskey="N" tabindex="1">
<label for="Email">E-mail:</label>
<input type="text" name="email" id="Email" accesskey="E" tabindex="1">
<label for="Phone">Phone Number:</label>
<input type="text" name="number" id="Number" tabindex="1">
<label for="Comment">Comments</label>
<textarea type="text" name="comment" id="Comment" rows="27" cols="70" tabindex="1"></textarea>
<input id="mySubmit" type="submit" value="Submit">
</form>
</fieldset>
</div>
email.php
<?php
if (isset($_POST['submit'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if (!$email)
echo "<script type='text/javascript'>alert('Please enter a valid email address...');history.back();</script>";
else {
$to = "randomemail#gmail.com"; //change this to YOUR email address
$name = (isset($_POST['name'])) ? $_POST['name'] : "anonymous";
$number = (isset($_POST['number'])) ? $_POST['number'] : "none";
$comment = (isset($_POST['comment'])) ? $_POST['comment'] : "none";
$subject = "Message from $name via contact form";
$message = "Name: $name\nNumber: $number\nEmail: $email\nMessage: $comment";
$from = "From: " . $name . "<" . $email .">\r\n" .
"Reply-To: " . $email ."\r\n" .
"X-Mailer: PHP/" . phpversion();
if (mail($to, $subject, $message, $from))
header("Location: thanks.html");
else
echo "<script type='text/javascript'>alert('An unknown system error has occurred!');history.back();</script>";
}
}
?>
when you submit, it loads email.php, but only a white page, not the thanks.html that it should.
You forgot to name your submit field:
<input id="mySubmit" type="submit" value="Submit" name="submit">
^^^^^^^^^^^^^
Don't use form fields to detect a post. Use the 100% reliable:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
instead. This will ALWAYS be true if a POST was performed. As you can see with your version, a simple typo or oversight will completely kill your logic.
First Empty your file and just put header("Location: thanks.html"); in your php tags. If it works then add the other lines progressively. you'll see the annoying line. Read about header on PHP reference website. It should be used carefully