I have a pre-made form built out of html/css/jquery/ajax. It is pretty much copy and pasted for the time being on my contact page.
This is what i call before my html tag on the contact.php page.
<?php
session_name("fancyform");
session_start();
$_SESSION['n1'] = rand(1,20);
$_SESSION['n2'] = rand(1,20);
$_SESSION['expect'] = $_SESSION['n1']+$_SESSION['n2'];
$str='';
if($_SESSION['errStr'])
{
$str='<div class="error">'.$_SESSION['errStr'].'</div>';
unset($_SESSION['errStr']);
}
$success='';
if($_SESSION['sent'])
{
$success='<h1>Success! We will be in contact!</h1>';
$css='<style type="text/css">#contact-form{display:none;}</style>';
unset($_SESSION['sent']);
}
?>
http://jsfiddle.net/6B2G7/
Here is a jsFiddle for the css/html/jquery. The page loads fine, you can fill in the fields and click submit. It successfully submits, but i receive no email. Spell checked the necessary items, but to no avail, no emails.
Any help is greatly appreciated. Sorry if i left anything out -- new here. Tried using firebug to see if there was an error, but i'm not getting any.
==EDIT==
This is my submit.php, which now i'm wondering where does this need to be? I don't think it's actually calling it anywhere on my site which would explain why no email is being sent. Now i'm a little confused -- first day with PHP. How do i get it to submit to the email address given in the code?
<?php
/* config start */
$emailAddress = 'coreymaret#hotmail.com';
/* config end */
require "phpmailer/class.phpmailer.php";
session_name("fancyform");
session_start();
foreach($_POST as $k=>$v)
{
if(ini_get('magic_quotes_gpc'))
$_POST[$k]=stripslashes($_POST[$k]);
$_POST[$k]=htmlspecialchars(strip_tags($_POST[$k]));
}
$err = array();
if(!checkLen('name'))
$err[]='The name field is too short or empty!';
if(!checkLen('email'))
$err[]='The email field is too short or empty!';
else if(!checkEmail($_POST['email']))
$err[]='Your email is not valid!';
if(!checkLen('subject'))
$err[]='You have not selected a subject!';
if(!checkLen('message'))
$err[]='The message field is too short or empty!';
if((int)$_POST['captcha'] != $_SESSION['expect'])
$err[]='The captcha code is wrong!';
if(count($err))
{
if($_POST['ajax'])
{
echo '-1';
}
else if($_SERVER['HTTP_REFERER'])
{
$_SESSION['errStr'] = implode('<br />',$err);
$_SESSION['post']=$_POST;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
exit;
}
$msg=
'Name: '.$_POST['name'].'<br />
Email: '.$_POST['email'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Message:<br /><br />
'.nl2br($_POST['message']).'
';
$mail = new PHPMailer();
$mail->IsMail();
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new ".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | contact form feedback";
$mail->MsgHTML($msg);
$mail->Send();
unset($_SESSION['post']);
if($_POST['ajax'])
{
echo '1';
}
else
{
$_SESSION['sent']=1;
if($_SERVER['HTTP_REFERER'])
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;
}
function checkLen($str,$len=2)
{
return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]),"utf-8") > $len;
}
function checkEmail($str)
{
return preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}
?>
Can you just run submit.php on your browser? Or check spam of your email and try with other email address..
http://tutorialzine.com/2009/09/fancy-contact-form/
You might also want to consider the Mandrill API for email. It's really simple to set up:
var m = new mandrill.Mandrill('your_api_key');
function sendTheMail(){
m.messages.send({
"message": {
"from_email": document.getElementById('from_email').value,
"from_name": document.getElementById('from_name').value,
"to":[{"email": "your_email", "name": "your_name"}],
"subject": "optional_value",
"text": document.getElementById('message').value
}
});
}
And you could then set up your contact page like this:
<p>Your Name: <input type="text" id="from_name"></p>
<p>Your Email: <input type="email" id="from_email"></p>
Message<br><br><textarea rows=15 cols=50 id="message"></textarea><br>
<button onclick="sendTheMail();">Send</button>
Related
I am trying to validate my RSVP form using only PHP. The user should receive an error message when the form is incomplete. I am trying to avoid the use of jQuery.
I am using this tutorial:
http://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
The form is functioning fine but I haven't been able to get the error messages to display at all. I am using Wordpress and I want the form to appear at the footer of every page; not sure if this complicates matters. Here is my code:
<?php
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='success'>{$message}</div>";
} else {
$response = "<div class='error'>{$message}</div>";
}
}
//response messages
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//variables defined for messages
$email = $_POST["rsvp_email"];
$name = $_POST["rsvp_name"];
$attend = $_POST["rsvp_attend"];
$number = $_POST["rsvp_number"];
//variables defined for message to admin
$to = get_option('admin_email'); //sending to wordpress admin email
$subject = "Just Kidding You Foo";
$headers = "From: $email\n";
$message = "$name $attend.\n RSVPs $number of people";
//conditional statements used for form validation
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
my_contact_form_generate_response("error", $email_invalid);
} else { //email is valid
//validate presence of name and message
if(empty($name) || empty($attend) || empty($number)) {
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to,$subject,$message,$headers);
if($sent) {
my_contact_form_generate_response("success", $message_sent); //message sent!
} else {
my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
?>
<div id="page-rsvp">
<h1>RSVP</h1>
<div id="respond">
<?php echo $response; ?>
<form action="<?php the_permalink(); ?>" method="post">
<!--Name here-->
<div class="rsvp-full"><label for="rsvp_name"><input type="text" name="rsvp_name" value="Your name"></label></div>
<div class="rsvp-full"><label for="rsvp_email"><input type="text" name="rsvp_email" value="Your email"></label></div>
<!--status of attendance-->
<div class="rsvp-full">
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="accepts">Accepts</div>
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="declines">Declines</div>
</div>
<!--number of guests attending-->
<div class="rsvp-full"><input type="number" name="rsvp_number" min="1" max="5">Total number of guests attending</div>
<div id="submit-button" class="rsvp-full"><input id="submit-button" type="submit"></div>
</form>
</div>
</div>
TIA!!!
I'm not that familiar with WP, but if I understand correctly, I believe you're trying to ensure all the fields are filled out.
Check your brackets! You need to be sure your curly brackets are opening and closing where you want them to. Otherwise the output of the page won't display. I write in all my braces because I'm not smart enough to be sure I know where they start and stop. I've taken the liberty of editing them into your question. I believe there was one missing at the end.
Once I fixed the brackets and removed functions my computer didn't have, it worked fine.
Tip 0: Try turning error reporting on for this script - error_reporting(E_ALL); at the top of this script. I always do for development.
Tip 1: use the placeholder attribute instead of value for things like "your name".
Tip 2: make sure the $_POST vars are set. I would do this by checking if they're set and then setting them to '' if they aren't; something like this:
//variables defined for messages
// you could do it like this:
if (isset($_POST["rsvp_email"])) {
$email = $_POST["rsvp_email"];
} else {
$email = '';
}
// or like this:
$name = '';
if (isset($_POST["rsvp_name"])) {
$name = $_POST["rsvp_name"];
}
// or even using a ternary operator:
$attend = isset($_POST["rsvp_attend"]) ? $_POST["rsvp_attend"] : '';
//but this will trigger a "Notice" error if the post var isn't set.
$number = $_POST["rsvp_number"];
I have a contact form, but the messages are not sending to the email I have declared. This is the submit.php file:
<?php
/* config start */
$emailAddress = 'xxxxxxx#hotmail.com';
/* config end */
require "../php/class.phpmailer.php";
session_name("fancyform");
session_start();
foreach($_POST as $k => $v)
{
if(ini_get('magic_quotes_gpc'))
$_POST[$k] = stripslashes($_POST[$k]);
$_POST[$k] = htmlspecialchars(strip_tags($_POST[$k]));
}
$err = array();
if(!checkLen('name'))
$err[] = 'The name field is too short or empty!';
if(!checkLen('email'))
$err[] = 'The email field is too short or empty!';
elseif(!checkEmail($_POST['email']))
$err[] = 'Your email is not valid!';
if(!checkLen('subject'))
$err[] = 'You have not selected a subject!';
if(!checkLen('message'))
$err[] = 'The message field is too short or empty!';
if((int)$_POST['captcha'] != $_SESSION['expect'])
$err[] = 'The captcha code is wrong!';
if(count($err))
{
if($_POST['ajax'])
{
echo '-1';
}
else if($_SERVER['HTTP_REFERER'])
{
$_SESSION['errStr'] = implode('<br />', $err);
$_SESSION['post'] = $_POST;
header('Location: '.$_SERVER['HTTP_REFERER']);
}
exit;
}
$msg =
'Name: '.$_POST['name'].'<br />
Email: '.$_POST['email'].'<br />
IP: '.$_SERVER['REMOTE_ADDR'].'<br /><br />
Message:<br /><br />
'.nl2br($_POST['message']).'
';
$mail = new PHPMailer();
$mail->IsMail();
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->AddAddress($emailAddress);
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->Subject = "A new ".mb_strtolower($_POST['subject'])." from ".$_POST['name']." | contact form feedback";
$mail->MsgHTML($msg);
$mail->Send();
unset($_SESSION['post']);
if($_POST['ajax'])
{
echo '1';
}
else
{
$_SESSION['sent'] = 1;
if($_SERVER['HTTP_REFERER'])
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;
}
function checkLen($str, $len = 2)
{
return isset($_POST[$str]) && mb_strlen(strip_tags($_POST[$str]), "utf-8") > $len;
}
function checkEmail($str)
{
return preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $str);
}
?>
If submit.php is opened in a browser, I get the following error message:
Warning: require(../php/class.phpmailer.php) [function.require]: failed to open stream:
No such file or directory in
/home/content/96/9227096/html/submit.php on line 10 Fatal error: require() [function.require]: Failed opening required
'../php/class.phpmailer.php'
(include_path='.:/usr/local/php5_3/lib/php') in
/home/content/96/9227096/html/submit.php on line 10
I was also told by my hosting server that I might need to add the following relay server in my code:(but I don't know where)
relay-hosting.secureserver.net
The statement require "../php/class.phpmailer.php"; means that the ../php/class.phpmailer.php file will be loaded and that if it can't be loaded then the script will terminate.
It is unable to load that script. That could be for any of a number of reasons. Maybe it's not there. Maybe the path you provided is wrong. Maybe it's a file permission issue. You'll have to figure that part out.
But since it can't load it, the script terminates with the error message.
I have encounter similiar problems on some hosting providers. Even if the path was good require did not include file and terminated whole script. You could write there a real path to your file, and maybe that will help. Since this problem I started to use
require(getcwd().'actual/path/relevant/to/index.php');
and starder to write apps in one class, similiar to Java or C# desktop apps.
I am trying to set up a web form for my website and I want to search the user's input for an # symbol and if it is not there, the form should not validate and a message should show up asking the user to recomplete the form.
Here's what I have so far:-
$at = "#";
if (is_null($at[$email]))
{
return FALSE;
}
I hope someone can help me!
<?php
$email = "someone#example.com";
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
echo "Valid email address.";
}
else {
echo "Invalid email address.";
}
?>
Or little bit more modern:
<?php
$email_address = "someone#example.com";
if (preg_match("/^[^#]*#[^#]*\.[^#]*$/", $email_address)) {
return "E-mail address";
}
?>
I got this code from a website and I have been altering it to fit my needs. The problem that I am facing is that the password reset page is not firing a new password off by php mail but instead it is refreshing the page and the user is stuck on a php include file and not the site.
I know some php but this seems to be beyond me. After 12+hrs of trying different things I am asking for help :)
I hope its an easy fix. Thanks in advance for your help and code snippets.
<?php
include 'dbc.php';
/******************* ACTIVATION BY FORM**************************/
if ($_POST['doReset']=='Reset')
{
$err = array();
$msg = array();
foreach($_POST as $key => $value) {
$data[$key] = filter($value);
}
if(!isEmail($data['user_email'])) {
$err[] = "ERROR - Please enter a valid email";
header("Location: index.html?p=unknownuser");
}
$user_email = $data['user_email'];
//check if activ code and user is valid as precaution
$rs_check = mysql_query("select id from users where user_email='$user_email'") or die (mysql_error());
$num = mysql_num_rows($rs_check);
// Match row found with more than 1 results - the user is authenticated.
if ( $num <= 0 ) {
$err[] = "Error - Sorry no such account exists or registered.";
header("Location: index.html?p=unknownuser");
//exit();
}
if(empty($err)) {
$new_pwd = GenPwd();
$pwd_reset = PwdHash($new_pwd);
//$sha1_new = sha1($new);
//set update sha1 of new password + salt
$rs_activ = mysql_query("update users set pwd='$pwd_reset' WHERE
user_email='$user_email'") or die(mysql_error());
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
//send email
$message =
"Here are your new password details ...\n
User Email: $user_email \n
Passwd: $new_pwd \n
Thank You
Administrator
$host_upper
______________________________________________________
THIS IS AN AUTOMATED RESPONSE.
***DO NOT RESPOND TO THIS EMAIL****
";
mail($user_email, "Reset Password", $message,
"From: \"Client Password Reset\" <clientservices#example.com>\r\n" .
"X-Mailer: PHP/" . phpversion());
header("Location: index.html?p=newpassword");
exit();
}
}
/*
mail($user_email, "Reset Password", $message,
"From: \"Client Registration\" <clientservices#example.com>\r\n" .
"X-Mailer: PHP/" . phpversion());
$msg[] = "Your account password has been reset and a new password has been sent to your email address.";
//header("Location: index.html?p=newpassword");
//$msg = urlencode();
//header("Location: forgot.php?msg=$msg");
//exit();
}
}
*/
?>
<script language="JavaScript" type="text/javascript" src="jquery/jquery-1.6.4.min.js"></script>
<script language="JavaScript" type="text/javascript" src="jquery/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#actForm").validate();
});
</script>
<?php
/******************** ERROR MESSAGES*************************************************
This code is to show error messages
**************************************************************************/
if(!empty($err)) {
echo "<div class=\"msg\">";
foreach ($err as $e) {
echo "* $e <br>";
}
echo "</div>";
}
if(!empty($msg)) {
echo "<div class=\"msg\">" . $msg[0] . "</div>";
}
/******************************* END ********************************/
?><div id="clientLogin">You are about to request a reset of your client account password | Login<br>
<form action="forgot.php" method="post" name="actForm" id="actForm" style="margin-top:5px;">
Your Email <input name="user_email" type="text" class="required email" id="txtboxn" size="25"><input name="doReset" type="submit" id="doLogin3" value="Submit" class="button"></form></div>
You have:
mail($usr_email, "Reset Password", $message...);
When it looks like you should have
mail($user_email, "Reset Password", $message...);
Notice you used $usr_email instead of $user_email.
That is why no email is being sent. Then it looks like the user is redirected to index.html?p=newpassword so depending on what that page is it may appear to just be reloading the same page.
UPDATE:
Also, you have the element doReset with a value of Submit and in your PHP code you are checking to see that $_POST['doReset'] == Reset instead of Submit.
<input name="doReset" type="submit" id="doLogin3" value="Submit" class="button">
Change
if ($_POST['doReset']=='Reset')
to
if ($_POST['doReset']=='Submit')
I have a system where the user sends an email using a form (simple).
HTML form
<form method="post" action="process.php">
<label class="fieldLabel">Your email:</label><label class="errorLabel"><?php echo $form->error("email"); ?></label>
<input type="text" name="email" maxlength="100" class="email" value="<?php echo $form->value("email"); ?>" />
<label class="fieldLabel">Your enquiry:</label><label class="errorLabel"><?php echo $form->error("body"); ?></label>
<textarea name="body" class="enquiry"><?php echo $form->value("body"); ?></textarea>
<input type="submit" name="enquiry" class="button" value="Send Message"/>
</form>
On the same page, I have this if statement
if(isset($_SESSION['enq'])){
if($_SESSION['enq']){
echo "<h2>Your message has successfully been sent to Alan Slough.</h2>";
}
else{
echo"<h2>Oops, something went wrong. Please try again.</h2>";
}
unset($_SESSION['enq']);
}
Now the process.php file the form directs to
class Process{
//class constructor
function Process(){
if(isset($_POST['enquiry'])){
$this->enquiry();
}
}
function enquiry(){
global $session, $form;
//Registration attempt
$retval = $session->enquiry($_POST['email'], $_POST['body']);
//Successful
if($retval == 0){
$_SESSION['enq'] = true;
header("Location: contact-us.php");
}
//Error found with form
else if($retval == 1){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: contact-us.php");
}
//Failed
else if($retval == 2){
$_SESSION['enq'] = false;
header("Location: contact-us.php");
}
}
};
And now the session page where everything happens
//enquiry being made
function enquiry($email, $body){
global $form;
//check email entered
$field = "email";
if(!$email || strlen($email = trim($email)) == 0){
$form->setError($field, "* Not entered");
}
//check body(s) entered
$field = "body";
if(!$body || strlen($body = trim($body)) == 0){
$form->setError($field, "* Not entered");
}
//if errors exist, send them back to the user
if($form->num_errors > 0){
return 1; //errors with form
}
else if($form->num_errors == 0){
$this->customerEnquiry($email, $body);
return 0; //successful
}
else{
return 2; //failed
}
}
//send the enquiry to the account email
function customerEnquiry($email, $body){
$from = "From: ".$email." <".$email.">";
$to = "random#email.com";
$subject = "Website enquiry from ".$email."";
return mail($to,$subject,$body,$from);
}
Ok my problem is that the errors aren't coming back if I don't fill in the form. Also, the success text isn't being displayed if I don't?
Anyone see a problem with how this flows?
Hoping I have just missed something simple!
Thanks!
I noticed this bit of code.
if(isset($_SESSION['enq'])){ // <---This...
if($_SESSION['enq']){ // <---And This
echo "<h2>Your message has successfully been sent to Alan Slough.</h2>";
}
else{
echo"<h2>Oops, something went wrong. Please try again.</h2>";
}
unset($_SESSION['enq']);
}
If $_SESSION['enq'] is not set, then the IF statement inside that will never execute, meaning you will see neither the success nor failure message.
Also, are you starting the session anywhere on the page? If you never start a session, then $_SESSION['enq'] will never be set.
http://www.php.net/manual/en/function.session-start.php
This is a very strange way to go about this. For example you're displaying success/failure message before the e-mail has been sent.
Have you copy and pasted this?
The usual method to do this would be to have the logic in process.php only, this is where you'd do your validation (return message to user if failed) and ultimately send the e-mail.
In the long run I think you'd be better off modifying the flow as I'm currently having a hard time trying to follow it.