Contact page template - redirect to 'thank you page' not working - forms

I'm trying to submit a form via custom page template but the problem is that it only works with form action="<?php the_permalink() ?>" and I need the form to be submitted and redirected to something like this form action="<?php bloginfo('url')?>/message-sent?id=<?php the_ID() ?>"
Full code:
<?php
$emailError = '';
if(isset($_POST['submitted'])) {
$email = trim($_POST['email']);
//setup self email address
$emailTo = $email;
$subject = "[reminder] Don't forget to download " . get_the_title();
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: Myemail reminders <no-reply#xyz.com>' . "\r\n";
wp_mail($emailTo, $subject, $body, $headers);
$emailSent = true;
} ?>
<section class="box grid_9 list_posts">
<div class="inner">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<div class="entry-content">
<div class="contact-form clearfix">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<?php _e('Thanks, your email was sent successfully.', 'framework') ?>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error"><?php _e('Sorry, an error occured.', 'framework') ?>
<?php } ?>
<form action="<?php the_permalink()?>" id="contactForm" method="post">
<ul class="contactform">
<li>
<input type="email" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" required="required" />
</li>
<li class="buttons">
<input type="hidden" name="submitted" id="submitted" value="true" />
<input type="submit" value="Remind Me!"></input>
</li>
</ul></form>
<?php } ?></div>
</div>
</div>
<?php endwhile; else: ?>
<div id="post-0" <?php post_class() ?>>
<h1 class="entry-title"><?php _e('Error 404 - Not Found', 'framework') ?></h1>
</div>
<?php endif; ?></div>
</section>
I got no php errors in log, page is redirected successfully, but no email is sent. When using the_permalink, everything works just fine.

When submitting the form data to a different script, make sure the code for (validating the input and) sending the email is in that very file.
Otherwise, your URL /message-sent might rewrite to a completely different script and the script with the above code isn't involved at all once the submit button gets clicked.
Did that held you? Feel free, to ask, if my wording is incomprehensible or if my description isn't clear to you

Maybe you forgot to put ".php" at the end of your /message-sent?id=xxx file, i.e /message-sent.php?id=xxx?
Another thought: It is always a good idea to filter the user input, because you will receive a lot of spam, put some sort of CAPTCHA validation code and sanitize/validate the whole user input text, i.e. every text, which comes from input fields of your form.
For email:
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
For name and comments:
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$comments = filter_var(strip_tags($_POST['comments']), FILTER_SANITIZE_STRING);

Related

Redirection not working after sending Email in CakePHP

I am sending a Email in Contact-Us form in CakePHP 2. Mail is being send properly but the problem is after sending Email it is not redirecting to Home page. I am using SMTP to send email.
My Controller method
public function contactForm()
{
if ($this->request->is(['post','put'])) {
$name = $this->request->data['home']['name'];
$email = $this->request->data['home']['email'];
$phone = $this->request->data['home']['phone'];
$message = $this->request->data['home']['message'];
$emailMessage = "Name - $name\n";
$emailMessage .= "Email - $email\n";
$emailMessage .= "Phone - $phone\n";
$emailMessage .= "Message - $message\n";
$Email = new CakeEmail();
$Email->config('smtp');
$Email->from(array($email =>$name));
$Email->to('info#myserver.com');
$Email->subject('Contact Us - Form');
$Email->send($emailMessage);
$this->Session->setFlash('Thank for contacting us. Our representative will reach you soon.','flash', array('alert'=> 'success'));
$this->redirect(array('action' => 'index'));
}
}
The index method is also there. Here is my HTML form
<?php echo $this->Form->create('home', array( 'controller' => 'homes', 'action' => 'contactForm','name'=>'contact-form','id'=>'contact-form','class'=>'contact-form'));?>
<div class="row flex-box">
<fieldset class="column column-1-2">
<label>YOUR NAME</label>
<?php echo $this->Form->input('name',array('type'=>'text','id'=>'name','value'=>'','label' => false,'class'=>'text-input validate[required]','div'=>false));?>
<label>YOUR EMAIL</label>
<?php echo $this->Form->input('email',array('type'=>'email','id'=>'email','value'=>'','label' => false,'class'=>'text-input validate[required]','div'=>false));?>
<label>YOUR PHONE</label>
<?php echo $this->Form->input('phone',array('type'=>'tel','id'=>'phone','value'=>'','label' => false,'class'=>'text-input validate[required]','div'=>false));?>
</fieldset>
<fieldset class="column column-1-2">
<label>MESSAGE</label>
<?php echo $this->Form->input('message',array('type'=>'textarea','id'=>'content','value'=>'','div'=>false));?>
</fieldset>
</div>
<div class="row margin-top-30">
<div class="column column-1-1">
<div class="row margin-top-15 padding-bottom-16 align-center">
<button type="submit" class="more submit-contact-form" style="display:inline-block;">Send message</button>
</div>
</div>
</div>
</form>
I am receiving mail properly. Not able to distinguish what is the error.
Any help will be appreciated.
Please check if you properly closed your PHP controller file and there should be no spaces after closing ?> PHP tags in controller file.
Also check other controllers for same.

PHP form submits regardless of required/error handling attempts

newbie here
I am currently attempting to build a simple contact form to learn how best to build one. I've tried to make several fields required (name, email, do you like spam radio button). The required html5 element isn't working for me or I am not implementing it correctly based on what i've read here, on google and other places. Likewise the error/require messages don't display if someone attempts to submit a message. Instead the form goes through on submit even if NO content anywhere has been entered. I built this yesterday and have been working on the errors for about 24 hours now and am hoping to find some help here.
I currently am returning no errors, the form sends all information entered as hoped, but it also sends if NO information is entered and that doesn't seem like the best possible form to me. I've tried to build a function to help the required, but that doesn't seem to be working either.
Again, i'm new so if my mistakes are obvious and silly, please help em to understand them, that would be greatly appreciated.
current example can be found here
My code:
<!-- For PoohPot -->
<style TYPE="text/css">
input[type="text"]#website { display: none; }
input#website { display: none; }
.vSmall {font-size: 50%; text-align: center;}
</style>
<script>
$('form').submit(function(){
if ($('input#website').val().length != 0) {
return false;
}
});
</script>
<?php
//template.php
include '_inc/config.php';//holds arrays, et al.
include '_inc/functions.php';//holds functions that call arrays, etc
include '_inc/head.php';//Begin Document
//include '_inc/header.php';//Begin Content
?>
<article class="container box style3">
<header>
<img src="_img/icons/icon_lg-max-o-matic2.png" alt="php icon">
<h2><?=NAME_SITE?></h2>
<p>Spam Survey</p>
</header>
<?php
$to = "chezshire#gmail.com";
$subject="Spam Survey";
//----- end conf ----- //
// define variables and set to empty values
$nameErr = $emailErr = $spamErr = "";
$userName = $userEmail = $userMessage = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["userName"]))
{$nameErr = "* Name is required";}
else
{$name = testInput($_POST["userName"]);}
if (empty($_POST["userEmail"]))
{$emailErr = "* Email is required";}
else
{$email = testInput($_POST["userEmail"]);}
if (empty($_POST["spamErr"]))
{$emailErr = "* You must select an option";}
else
{$email = testInput($_POST["userEmail"]);}
if (empty($_POST["userMessage"]))
{$comment = "";}
else
{$comment = testInput($_POST["userMessage"]);}
}
if(isset($_POST['userName']))
{//data is submitted, show it
//echo $_POST['userName'];
$text = 'From: ' . $_POST['userName'] . PHP_EOL;
//$text .= $_POST['Comments']; //add on to text
$text .= process_post(); // uses proces_post to handle comments and stuff
$from = $_POST['userEmail'];
/*
echo '<pre>';
var_dump($_POST);
echo '</pre>';
*/
//domain spoofing controls
$headers = 'From: noreply#max-o-matic.com' . PHP_EOL . //from where formhandler sits
'Reply-To: ' . $from . PHP_EOL . //where replies are to go to
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $text, $headers); //from becomes headers
echo '<div class="row">
<div class="12u">
<p>Thanxs!</p>
<p>
<br />RESET
</p>
</div>
</div>
</article>
';
/*
echo '<pre>';
var_dump($_POST);
echo '</pre>';
*/
}else{//no data, show form
echo '
<form action="' . THIS_PAGE . '" method="post">
<div class="row half">
<div class="6u">
<input type="text" class="text" name="userName" placeholder="Name?" required autofocus />
<span class="error"><?php echo $nameErr;?></span>
</div>
<div class="6u">
<input type="text" class="text" name="userEmail" placeholder="Email" required />
<span class="error"><?php echo $emailErr;?></span>
</div>
</div>
<div class="row half">
<div class="6u">
Do you like spam?<br />
<input type="radio" name="Please_Spam_Me" value="YES!" required value="1" />Yes<br />
<input type="radio" name="Please_Spam_Me" value="NO!" />No<br />
<span class="error"><?php echo $spamErr;?>
</div>
<div class="6u">
How much Spam is too much?<br />
<input type="checkbox" name="checkbox-group" class="group-required" id="checkbox-group-id" value="6+" >6 or more<br />
<input type="checkbox" name="checkbox-group" value="2+">2 to 5<br />
<input type="checkbox" name="checkbox-group" value="Any">ANY<br /><br />
</div>
</div>
<!--For Winnie the Pooh -->
<input id="website" name="website" type="text" value"Website" />
<div class="row half">
<div class="12u">
<textarea name="userMessage" placeholder="What is your opinion on Spam?"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>SEND!</li>
<input type="submit" />
</ul>
<p class="vSmall">
* Please note, instead of a reCaptcha I build my own \'honeypot\' from scratch.
</p>
</div>
</div>
</form>
</article>
';
}
function testInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// this is a function
function process_post()
{//loop through POST vars and return a single string
$myReturn = ''; //set to initial empty value
foreach($_POST as $varName=> $value)//$_POST is an array
{#loop POST vars to create JS array on the current page - include email
$strippedVarName = str_replace("_"," ",$varName);#remove underscores
if(is_array($_POST[$varName]))
{#checkboxes are arrays, and we need to collapse the array to comma separated string!
$myReturn .= $strippedVarName . ": " . implode(",",$_POST[$varName]) . PHP_EOL;
}else{//not an array, create line
$myReturn .= $strippedVarName . ": " . $value . PHP_EOL;
}
}
return $myReturn;
}
include "_inc/footer.php";//End Content/Document
?>
If you're trying to use HTML5 stuffs then you need the HTML5 doctype. Place this at the start of your output and see what happens:
<!DOCTYPE html>
Also, typo value"Website" should be value="Website"

Handle two different forms in a single page

So I want to handle two forms on one single page, and I've got some problems to do it; I've got a module named 'contact', here is the indexSucces.php
<div id="registerForm">
<form action="<?php echo url_for('contact'); ?>" method="post" id="loginForm">
<?php foreach ($loginForm as $widget): ?>
<?php if(!$widget->isHidden()) { ?>
<?php echo $widget->renderRow(); ?>
<?php } else { ?>
<?php echo $widget->render() ?>
<?php } ?>
<?php endforeach; ?>
<br/><input type="submit" id="loginSubmit" class="btn primary" value="<?php echo __('Envoyer'); ?>" />
</form>
</div>
<div id="registerForm">
<form action="<?php echo url_for('contact'); ?>" method="post" id="registerForm">
<?php foreach ($registerForm as $widget): ?>
<?php if(!$widget->isHidden()) { ?>
<?php echo $widget->renderRow(); ?>
<?php } else { ?>
<?php echo $widget->render() ?>
<?php } ?>
<?php endforeach; ?>
<br/><input type="submit" id="registerSubmit" class="btn primary" value="<?php echo __('Envoyer'); ?>" />
</form>
</div>
Is it possible to handle that in a single action page ? I need to know the way on how to it, I'm stuck since yesterday. For exemple, when I want to submit the first form, it wants to submit the second form with.
Someone can provide me an exemple ? I can post my sh** action page if you want to see how I tried to handle that.
Thanks in advance !
EDIT:
I made this code according to your advice :
public function executeIndex(sfWebRequest $request)
{
$this->loginForm = new loginForm();
$this->registerForm = new registerForm();
$this->processForm($request, $this->loginForm, $this->registerForm);
}
public function processForm(sfWebRequest $request, sfForm $loginForm, sfForm $registerForm)
{
if($request->hasParameter('login'))
{
if($request->isMethod('post'))
{
$loginForm->bind($request->getParameter($loginForm->getName()));
if($loginForm->isValid())
{
$this->redirect('payement');
}
}
} elseif ($request->hasParameter('register'))
{
if($request->isMethod('post'))
{
$registerForm->bind($request->getParameter($registerForm->getName()));
if($registerForm->isValid())
{
$this->redirect('payement');
}
}
}
}
The registerForm is submitting correctly, I can see the errors I've made in the form etc, and if it's correct, it is correctly redirected. But when I submit the loginForm, here is the error :
Argument 1 passed to sfForm::bind() must be an array, string given : on this line
$loginForm->bind($request->getParameter($loginForm->getName()));
Why ?
Yes, you can.
Add a name attribute to your buttons (i.e. login and register), and modify your action to:
if ($request->hasParameter("login")) {
// handle login
}
elseif ($request->hasParameter("register")) {
// handle register
}

Contact form with file attachment?

I have a contact form which is a template for pages on wordpress that I use if I need a contact form. All works fine but I want to add the capability of adding a file attachment so when the user fills in their name etc they can upload a photo and that photo will be sent to be me as an attachment.
I have a perfect working contact form and I only want to add that functionality to it. All my current code does all this it sends the name of the person their email address and their message to my email, all I'm missing is the attachment feature. I've been looking at alot of contact forms with this feature but to integrate that feature to my sendmail.php seems very hard as the coding style is completely different. Here is a demo of this in action. demo
This is my php file that has the form in it.
<?php get_header(); ?>
<script type="text/javascript">
$(document).ready(function(){
$('#contact').ajaxForm(function(data) {
if (data==1){
$('#success').fadeIn("slow");
$('#bademail').fadeOut("slow");
$('#badserver').fadeOut("slow");
$('#contact').resetForm();
}
else if (data==2){
$('#badserver').fadeIn("slow");
}
else if (data==3)
{
$('#bademail').fadeIn("slow");
}
});
});
</script>
<!-- begin colLeft -->
<div id="colLeft">
<!-- Begin .postBox -->
<div class="postBox">
<div class="postBoxTop"></div>
<div class="postBoxMid">
<div class="postBoxMidInner first clearfix">
<h1>Contact Us</h1>
<p><?php echo get_option('alltuts_contact_text')?></p>
<p id="success" class="successmsg" style="display:none;">Your email has been sent! Thank you!</p>
<p id="bademail" class="errormsg" style="display:none;">Please enter your name, a message and a valid email address.</p>
<p id="badserver" class="errormsg" style="display:none;">Your email failed. Try again later.</p>
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"></textarea><br />
<input type="submit" id="submitinput" name="submit" class="submit" value="SEND MESSAGE"/>
<input type="hidden" id="receiver" name="receiver" value="<?php echo strhex(get_option('alltuts_contact_email'))?>"/>
</form>
</div>
</div>
<div class="postBoxBottom"></div>
</div>
<!-- End .postBox -->
</div>
<!-- end colleft -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
and here is the file that handles the sending of the mail.
<?php
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(mail($to, $subject, $message, $headers))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
Thanks!
You can read this simple tutorial to know what needs to be done to add file upload support to your current form:
http://www.tizag.com/phpT/fileupload.php
Hope it helps!
EDITED
After the upload process, you can do like this:
if (file_exists($_FILES['uploaded']['tmp_name'])) {
$mail->AddAttachment($_FILES['uploaded']['tmp_name'], $_FILES['uploaded']['name']);
}
What this does is to add an attachment to your email by calling the AddAttachment from PHPMailer, and using the file just uploaded from the TMP folder of your server... so no actual storage of the file is necessary.
You can use
http://wordpress.org/plugins/contact-form-7/
It has a option for Upload field as well as all validations, really easy to use.
You just need to enter shortcode and you can use the contact form anywhere you want.

Zend_Form: when print elements of form in view- form tag dod't created

Problem:
When print elements of form in view, form tag don't created
My View:
<?php
/****** print elements and inser label:: have to be done in this way for integrate cushycms ********/
echo $this->form->empty;
?>
<label>Ad Title</label>
<?php
echo $this->form->adtitle;
?>
<label></label>
<?php echo $this->form->adbody; ?>
MY Form (part of the code):
class MyForm extends Zend_Form
{
function init(){
$empty = new Zend_Form_Element_Hidden("empty");
$empty->removeDecorator('Label');
$title = new Zend_Form_Element('adtitle');
$title->removeDecorator('Label');
$title//->setLabel('Ad Title')
->setRequired('true')
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty')
->setAttrib('MAXLENGTH',100)
->setAttrib('Size',106);
$title->getValidator('NotEmpty')
->setMessage('Company Name can not be empty');
$body = new Zend_Form_Element_Textarea('adbody');
$body->removeDecorator('Label');
}
}
The html that I get (form tag not exist):
<dd id="empty-element">
<input type="hidden" name="empty" value="" id="empty"></dd> <label>Ad Title</label>
<dd id="adtitle-element">
<input type="text" name="adtitle" id="adtitle" value="" MAXLENGTH="100" Size="106"></dd><label></label>
<dd id="adbody-element">
<textarea name="adbody" id="adbody" onKeyDown="javascript:limitText(this.form.countdown,400)" onKeyUp="javascript:limitText(this.form.countdown,400)" rows="24" cols="80"></textarea></dd> <label>chras left (maximum 400): </label>
Thank you very much
I think you have to add the form tag by your self.
<form action="<?= $this->escape($this->form->getAction() ?>"
method="<?= $this->escape($this->form->getMethod() ?>"
>
Or use
echo $this->form;