Wordpress Custom Contact Form Not Working - php

I am trying to create a custom contact form page for my Wordpress theme. However on my way to finishing my codes the error message on my page won't show up.
Also, I am running on a localhost computer for testing this custom page and it seems it won't send my message to the ADMIN EMAIL that was set on my Wordpress Installation.
Here's the snippet on my WP Custom Contact Form:
<?php
/* Template Name: Contact Page */
?>
<?php
// Function for email address validation
function isEmail($verify_email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$verify_email));
}
$error_name = false;
$error_email = false;
$error_subject = false;
$error_message = false;
if (isset($_POST['submit'])) {
// Initialize the variables
$contact_name = '';
$contact_email = '';
$contact_subject = '';
$contact_message = '';
// Get the name
if (trim($_POST['contact_name']) === '') {
$error_name = true;
} else {
$name = trim($_POST['contact_name']);
}
// Get the email
if (trim($_POST['contact_email']) === '' || !isEmail($_POST['contact_email'])) {
$error_email = true;
} else {
$email = trim($_POST['contact_email']);
}
// Check if we have errors
if (!$error_name && !$error_email && !$error_subject && !$error_message) {
// Get the receiver email from the WP admin panel
$receiver_email = get_option('admin_email');
$subject = "Message from $contact_name";
$body = "You have a new quote request from $contact_name. Project details:" . PHP_EOL . PHP_EOL;
$body .= PHP_EOL . PHP_EOL;
$headers = "From: $contact_email" . PHP_EOL;
$headers .= "Reply-To: $contact_email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
// If all is good, we send the email
if (mail($receiver_email, $subject, $body, $headers)) {
$email_sent = true;
} else {
$email_sent_error = true;
}
}
}
?>
<?php get_header(); ?>
<!-- BLOG AREA -->
<section>
<hr class="no-margin" />
<div class="blog-container section-content">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="box-layer custom-padding">
<div class="align-center">
<h2>We want to hear from you!</h2>
<p>If you are seeking to contact us, please fill up the form below. If you want to advertise or be partner with us just inform us on the message box below. </p>
<p>Thank you so much for your support!
<br/>We really appreciate!</p>
<?php if (isset($email_sent) && $email_sent == true) : ?>
<h2>Success!</h2>
<p>You have successfully sent the quote request. I'll get back to you as soon as possible.</p>
<?php elseif (isset($email_sent_error) && $email_sent_error == true) : ?>
<h2>There was an error!</h2>
<p>Unfortunately, there was an error while trying to send the email. Please try again.</p>
<?php else : ?>
<form action="<?php the_permalink(); ?>" method="POST" class="general-form" novalidate>
<p <?php if ($error_name) echo 'class="error"'; ?>><input name="contact_name" id="contact_name" class="form-control" placeholder="Your Name.." type="text" value="<?php if (isset($_POST['contact_name'])) echo $_POST['contact_name']; ?>" /></p>
<p <?php if ($error_email) echo 'class="error"'; ?>><input name="contact_email" id="contact_email" class="form-control" placeholder="Your Email.." type="email" value="<?php if (isset($_POST['contact_email'])) echo $_POST['contact_email']; ?>" /></p>
<p <?php if ($error_subject) echo 'class="error"'; ?>><input name="contact_subject" id="contact_subject" class="form-control" placeholder="Your Subject.." type="text" value="<?php if (isset($_POST['contact_subject'])) echo $_POST['contact_subject']; ?>"/></p>
<p <?php if ($error_message) echo 'class="error"'; ?>><textarea name="contact_message" id="contact_message" class="form-control" placeholder="Write your comment here.." rows="4" cols="100"><?php if (isset($_POST['contact_message'])) echo $_POST['contact_message']; ?></textarea></p>
<input class="btn btn-primary no-border" name="submit" type="submit" id="submit" value="Send Message">
</form>
<?php endif; ?>
</div>
</div>
<!-- RELATED ARTICLE AREA -->
</div>
<aside>
<!-- SIDEBAR AREA -->
<div class="col-md-3 col-md-offset-1 margin-sidebar">
<?php get_sidebar(); ?>
</div>
</aside>
</section>
<?php get_footer(); ?>
Any idea? or Is there a way you can correct my code if you see some errors?

To get you started
Make sure WP_DEBUG is set to true on your wp-config.php file.
You can get the last errors from mail() (answered here)
Use wordpress' functions if available, in this case wp_mail is at your disposal.
There are wordpress plugins such as gravity forms or contact form 7 which can accomplish the task.
Use filters and actions.
Had to post as an answer, couldn't comment yet.
HTH

If you would like to get the admin email address, you have to do it with:
$bloginfo = get_bloginfo( 'admin_email' );
get_option('admin_email') is only works when you save anything to that in the Theme Setup, probably it is empty now.
By the way, you can find many of professional, ready to use solution, like WordPress Contact Form Slider

<?php
/*
Plugin Name:Contact Form Plugin
Plugin URI: http://example.com
Description: Simple non-bloated WordPress Contact Form
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
*/
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'form/form.php');
include( MY_PLUGIN_PATH . 'admin/admin-menu.php');
include( MY_PLUGIN_PATH . 'database/table.php');
?>
Form.php
====================
<?php
function form()
{
echo '<form action="'.esc_url($_SERVER['REQUEST_URI']).'" method="post">';
echo '<p>';
echo 'Your First Name:';
echo '<br/>';
echo '<input type="text" name="fname" required/>';
echo '<br/>';
echo 'your Email-Id:';
echo '<br/>';
echo '<input type="email" name="email" required/>';
echo '<br/>';
echo 'Your Subject:';
echo '<br/>';
echo '<input type="text" name="subject" required/>';
echo '<br/>';
echo 'Your Message:';
echo '<br/>';
echo '<textarea name="message" cols="30" rows="4" required></textarea>';
echo '<br/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
}
if(isset($_REQUEST['submit']))
{
$name = $_POST['fname'];
$email = $_POST['email'];
$subject=$_POST['subject'];
$msg=$_POST['message'];
function insertuser($name,$email,$msg,$subject){
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$wpdb->insert($table_name, array('name' => $name, 'email' => $email , 'message'=> $msg , 'subject' => $subject) );
}
insertuser($name,$email,$msg,$subject);
}
function shortcode()
{
form();
}
add_shortcode('contact-form','shortcode');
?>
table.php
===================
<?php
global $wpdb;
$table_name = $wpdb->prefix . "contactinfo";
$charset_collate = $wpdb->get_charset_collate();
if( $wpdb->get_var ('SHOW TABLE LINK' .$table_name) != $table_name )
{
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
email varchar(40) NOT NULL,
message text NOT NULL,
subject text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
?>

Related

How to get a wordpress post custom filed value and assign it to a variable?

I am creating a form that sends the form's details to my email.
My custom field is:
My function.php
function getHotel_contact_number() {
global $wp_query;
$postid = $wp_query->post->ID;
$getHotel_contact_number = get_post_meta($postid, 'hotel_contact_number', true);
$getHotel_contact_number;
}
And my form is:
<?PHP
$errors = array();
if (isset($_POST["submit"])) {
$to = "myemail#email.com";
$subject = "This is my subject";
$hotel = get_permalink();
$hotel_contact_nmbr = getHotel_contact_number();
$headers = array('From: '.$_POST['sendername'].' <'.$_POST['senderEmail'].'>');
//Check the name and make sure that it isn't a blank/empty string.
if(empty($sender)){
//Blank string, add error to $errors array.
$errors['sendername'] = "Please enter your name!";
}
if(empty($senderEmail)){
//Blank string, add error to $errors array.
$errors['senderEmail'] = "Please enter your email!";
}
$mailBody = "<h3>Hotel Details</h3><br/>
$hotel<br/>
$hotel_contact_nmbr<br/>"
$mail_sent = wp_mail( $to, $subject, $mailBody, $headers );
}
if ($mail_sent) { ?>
<h1 style="color: #007f00;">Request sent.</h1>
<?php
} else {
?>
<form id="" name="" action="<?php echo get_permalink(); ?>" method="post">
<div class="label-input-wrapper">
<div class="form-label">Name</div>
<div class="form-input">
<input type="text" name="sendername" value="<?PHP if(!empty($errors)) { echo $sender;} ?>" />
<div class="error-msg">
<?php if(isset($errors['sendername'])) { echo '<span style="color: red">'.$errors['sendername'].'</span>'; } ?>
</div>
</div>
</div>
<div class="label-input-wrapper">
<div class="form-label">E-Mail</div>
<div class="form-input">
<input type="email" name="senderEmail" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required value="<?PHP if(!empty($errors)) { echo $senderEmail;} ?>" />
<div class="error-msg">
<?php if(isset($errors['senderEmail'])) { echo '<span style="color: red">'.$errors['senderEmail'].'</span>'; } ?>
</div>
</div>
</div>
<input type="submit" value="Submit" name="submit">
</form>
<?php
}
?>
But when the form is submitted I am getting just a blank value for hotel contact number. What I am doing wrong? How can get the proper custom filed value when the form is submitted?
Anyhow it's working fine if I use hidden fields for this as I mentioned here:
Have a look at the bottom area of that question where I mention about hidden fields.
Change function with following code:
function getHotel_contact_number() {
global $wp_query;
$postid = $wp_query->post->ID;
$getHotel_contact_number = get_post_meta($postid, 'hotel_contact_number', true);
return $getHotel_contact_number;
}

Form $_SESSION data Issue

I have designed a form which check validation when it is sent, I am using Swiftmailer and all of the validation works however I have a problem. When I return back to the contact form the errors are still there if they filled it out wrong so...
name is required!
email is required!
the errors only go when it passes validation.
How do I refresh the page when the user leaves and comes back to a fresh form?
Contact form:
<?php
session_start();
?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Send a message</title>
</head>
<body>
<div class="container">
<div <?php if(isset($_SESSION['form_message'])) { echo 'style="color: green"'; } elseif (isset($_SESSION['form_errors'])) { echo 'style="color: red"'; } ?>>
<?php
if(isset($_SESSION['form_message']))
{
echo $_SESSION['form_message'];
unset($_SESSION['form_data']);
}
elseif(isset($_SESSION['form_errors']))
{
echo '<b>You have the following errors:</b>';
echo "<br>";
foreach($_SESSION['form_errors'] as $display_err) {
echo $display_err . "<br>";
}
}
?>
</div>
<form name="contact" method="post" action="swift_mail.php">
<div>
<label for="name">Full name</label><br />
<input type="text" name="name" id="name" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['name'] ; } ?>" />
</div>
<div>
<label for="email">Email Address</label><br />
<input type="text" name="email" id="email" value="<?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['email'] ; } ?>" />
</div>
<div>
<label for="comment">Comment</label><br />
<textarea name="comment" id="comment"><?php if(isset($_SESSION['form_data'])) { echo $_SESSION['form_data']['comment'] ; } ?></textarea>
<input type="submit" value="submit" name="submit_msg"/>
</div>
</form>
</div>
</body>
</html>
</code>
swift
<?php
session_start();
require_once 'Swift-5.0.3/lib/swift_required.php';
require 'vendor/autoload.php';
if(isset($_POST['submit_msg'])) {
/*
Validate data before it is posted
*/
$rule_set = array (
'name' => array(
'required'
),
'email' => array(
'required'
),
'comment' => array(
'required'
)
);
/*
Checking Validation
*/
$validation_result = SimpleValidator\Validator::validate($_POST, $rule_set);
if ($validation_result->isSuccess() == true ) {
/*
Contact Form Information
*/
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Main Point of contact
$email_address = 'ben#bubbledesign.co.uk';
// Composed Message
$body_msg = "Name: " . $name . "<br>" . "Comments: " .$comment;
/*
Swift Mail Transport
*/
$transport = Swift_MailTransport::newInstance();
$mail = Swift_Mailer::newInstance($transport);
/*
Create the Swift Message
*/
$message = Swift_Message::newInstance('Subject line')
->setFrom($email)
->setTo($email_address)
->setBody($body_msg, "text/html");
/*
Send Swift Message
*/
$result = $mail->send($message);
$_SESSION['form_message'] = "Thank you for your message someone will be in touch soon.";
unset($_SESSION['form_errors']);
unset($_SESSION['form_data']);
header('location: contact-form.php');
} else {
$_SESSION['form_data'] = $_POST;
$_SESSION['form_errors'] = $validation_result->getErrors();
header('Location: contact-form.php');
}
}
?>

ReferenceError: $ is not defined in sendmail.php

let me apologize in advance, i just jumped into the jquery thing like yesterday, so speak slowly and use lots of beginner terms. anyway, im trying to make my jquery/ajax contact form stop refreshing and stay on the same page, but i keep receiving an error reading "ReferenceError: $ is not defined". i trying to fix this and figure out if it is related to my failure here.
here is the HTML......
<div id="contact">
<h2>Contact</h2>
<div class="clear"></div>
<div class="contactContainer">
<h3>Get in touch:</h3>
<div class="contact">
<form action="js/ajaxcontactform/sendmail.php" method="post" id="contactForm">
<ul>
<li>
<label for="name">Name:<font color="#ff3300">*</font></label>
<input type="text" name="name" value="" id="name" />
</li>
<li>
<label for="email">Email:<font color="#ff3300">*</font></label>
<input type="text" name="email" value="" id="email" />
</li>
<li>
<label for="tele">Telephone:</label>
<input type="text" name="tele" value="" id="tele" />
</li>
<li class="special" style="display: none;">
<label for="last">Don't fill this in:</label>
<input type="text" name="last" value="" id="last" />
</li>
<li>
<label for="message">Message:<font color="#ff3300">*</font></label><textarea rows="5" name="message"></textarea>
</li>
<li class="submitbutton">
<input type="submit" class="btn" value="Send Message" />
</li>
</ul>
</form>
here is the php.....
<?php
// basic settings section
$sendto = 'your#email.com';
$subject = 'You have a new message from your virtual resume!';
$iserrormessage = 'There was a problem with sending e-mail to us, please check:';
$thanks = "Thank's for your message! I'll contact you as soon as possible!";
$emptyname = 'Did you enter your name?';
$emptyemail = 'Did you enter your e-mail address?';
$emptymessage = 'Did you enter the message?';
$emptyphone = 'Did you enter phone number?';
$alertname = 'Please enter your name with standard alphabet!';
$alertemail = 'Please enter your e-maill address in format: name#domain.com';
$alertmessage = "Please do not use any parenthesis or other escaping characters. Standard web url's should work fine!";
$alertphone = 'Please enter your phone number without any special characters, only numbers ex: 5553212';
$alert = '';
$iserror = 0;
// cleaning the post variables
function clean_var($variable) {$variable = strip_tags(stripslashes(trim(rtrim($variable))));return $variable;}
// validation of filled form
if ( empty($_REQUEST['name']) ) {
$iserror = 1;
$alert .= "<li>" . $emptyname . "</li>";
} elseif ( ereg( "[][{}()*+?.\\^$|]", $_REQUEST['name'] ) ) {
$iserror = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$iserror = 1;
$alert .= "<li>" . $emptyemail . "</li>";
} elseif ( !eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $_REQUEST['email']) ) {
$iserror = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$iserror = 1;
$alert .= "<li>" . $emptymessage . "</li>";
} elseif ( ereg( "[][{}*+\\^|]", $_REQUEST['message'] ) ) {
$iserror = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
// if there was error, print alert message
if ( $iserror==1 ) {
echo "<script type='text/javascript'>$(\".message\").hide(\"slow\").fadeIn(\"slow\").delay(5000).fadeOut(\"slow\"); </script>";
echo "<strong>" . $iserrormessage . "</strong>";
echo "<ul>";
echo $alert;
echo "</ul>";
} else {
// if everything went fine, send e-mail
$msg = "From: " . clean_var($_REQUEST['name']) . "\n";
$msg .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$msg .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
mail($sendto, $subject, $msg, $header);
echo "<script type='text/javascript'>$(\".message\").fadeOut(\"slow\").fadeIn(\"slow\").animate({opacity: 1.0}, 5000).fadeOut(\"slow\");</script>";
echo $thanks;
die();
}
?>
im using the standard jquery.form.js (as far as i know)
thanks again in advance!
Looking at your actual site, I see that not all you JS includes are being found in the folders you specify. In particular this is the case for jquery.form.js. Since this plugin is not found, the page naturally refreshes when you submit the form.
Looking at the HTML, I found this line:
<script type="text/javascript" src="/js/ajaxcontactform/jquery.form.js"></script>
If you look for http://www.robergeaz.com/js/ajaxcontactform/jquery.form.js, you will see that it does not exist.
Looking at you other JS locations I see that most of them use the relative path js/xyz.js, which is equivalent to http://www.robergeaz.com/darin/js/xyz.js. Using the same relative path as the other plugins for your form plugin shows a valid location at http://www.robergeaz.com/darin/js/ajaxcontactform/jquery.form.js.
So to solve your problem, change the above script to:
<script type="text/javascript" src="js/ajaxcontactform/jquery.form.js"></script>
Note the missing / at the beginning of the src.
Edit:
Also, you need to load the plugins AFTER you include the main jQuery library.
Do you importing the jquery lib?
Try to put it in your code head.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Form submitting to a different url as opposed to within the same page

I have a form that submits within the same url (eg. form.co.uk is where the form is and upon successfully submitting rather than going to a confirmation page with a different URL it stays on form.co.uk and gives the 'thanks for contacting us' confirmation on the same page.
However I need to change this so upon submitting it goes to a different url (just a thank you page)
How would I go about this?
html
<div class="width-inner">
<?if ($c->submitted && count($c->errors) == 0): ?>
<div class="thankyou-box">
<h2>Thank you for your enquiry</h2>
<h3>We'll get back to you as soon as we can.</h3>
</div>
<script type="text/javascript">
_gaq.push(['_trackPageview', "/thanks"]);
</script>
<? else: ?>
<div class="contact-box left" style="width:650px;">
<form action="form.php" method="post">
<div class="heading">
<h2>Contact Us</h2>
<h3>Get in touch now.</h3>
</div>
<? if(count($c->errors) > 0): ?>
<div class="error">
There was a problem with your enquiry
</div>
<? endif; ?>
<div class="vspace20"></div>
<label>Your Name:</label>
<input type="text" name="name" class="<?= $c- >requestEmpty('name') ? 'invalid' : '' ?>" value="<?= #$_REQUEST['name'] ?>"/>
<div class="required">Required field</div>
<div class="clear"></div>
<label>Email Address:</label>
<input type="email" name="email" class="<?= $c- >requestEmpty('email') ? 'invalid' : '' ?>" value="<?= #$_REQUEST['email'] ?>"/>
<div class="required">Required field</div>
<div class="clear"></div>
<hr/>
<label>Enquiry:</label>
<textarea name="enquiry" class="<?= $c->requestEmpty('enquiry') ? 'invalid' : '' ?>">I would like to contact you.</textarea>
<div class="clear"></div>
<hr/>
<input type="hidden" name="extra" value="<?= #$_REQUEST['extra'] ?>"/>
<div class="notice">Your details will not be used for marketing purposes</div> <br>
<input type="submit" class="btn-submit right" value="Claim Now" name="submit"/>
<div class="clear"></div>
</form>
</div>
</div>
code for the handler
<?php
class Contact {
var $submitted = false;
var $errors = array();
var $template = "Name: %s\r\nEmail Address: %s\r\nEnquiry: %s";
public function __construct() {
if (!empty($_REQUEST['submit'])) {
$this->submitted = true;
} else {
return;
}
$requiredFields = array(
'name', 'email'
);
foreach($requiredFields as $key) {
if ($this->requestEmpty($key)) {
$this->errors[] = $key;
}
}
if (count($this->errors) == 0) {
$this->_sendForm();
}
}
private function _sendForm() {
$body = sprintf($this->template,
$_REQUEST['name'],
$_REQUEST['email'],
$_REQUEST['enquiry'] . "\r\n" . $_REQUEST['extra']);
$headers = 'From: auto#magnetikmedia.co.uk' . "\r\n" .
'Reply-To: auto#magnetikmedia.co.uk' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail("johnfarrell2012#gmail.com", "New contact form", $body, $headers, "- fauto#magnetikmedia.co.uk");
header("Location: thank_you.php");
exit;
}
public function requestEmpty($key) {
if (empty($_REQUEST['submit'])) {
return false;
}
if (!isset($_REQUEST[$key])) {
return true;
}
if (trim($_REQUEST[$key]) == "") {
return true;
}
return false;
}
}
?>
I guess it must be something to do with the top if else statement ie. I want to say 'if successful and no errors then go to www.whatever.com' but how would I write this?
At the end of your form PHP page, add this, altered for your URL:
$success = "success.html";
header("Location: " . $success);
Maybe you just need to change your HTML,
<form action='page.php' method='post'>
or send a header after your PHP is handled on that same page, like
header('LOCATION:page.php'); die();
. Make sure you use die(); to kill the current page.
After seeing your edit, try this then:
Quick opening note: You could also set header to an external URL such as:
header("Location: http://www.example.com/");
and the http:// must be included.
Redirection after mail examples:
mail("johnfarrell2012#gmail.com", "New contact form", $body, $headers, "- fauto#magnetikmedia.co.uk");
header("Location: thank_you.php");
exit;
}
And to check if mail was sent successfully:
(We simply add an if/else condition.)
if(mail("johnfarrell2012#gmail.com", "New contact form", $body, $headers, "- fauto#magnetikmedia.co.uk"));
header("Location: thank_you.php");
exit;
}
else {
echo "Mail not sent";
exit;
}
More on the header function can be viewed on the PHP.net Website.
http://php.net/manual/en/function.header.php

PHP contact form isn't working when first installed

I just installed a new PHP contact form but it isn't working. I already tried to fix it but I can't figure out how to fix it. Can somebody take a look at it and give me a fix?
The PHP code:
$to = 'email#hotmail.com';
$subject = 'Contact';
$contact_submitted = 'Your message has been sent.';
function email_is_valid($email) {
return preg_match('/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i',$email);
}
if (!email_is_valid($to)) {
echo '<p style="color: red;">You must set-up a valid (to) email address before this contact page will work.</p>';
}
if (isset($_POST['contact_submitted'])) {
$return = "\r";
$youremail = trim(htmlspecialchars($_POST['your_email']));
$yourname = stripslashes(strip_tags($_POST['your_name']));
$yourmessage = stripslashes(strip_tags($_POST['your_message']));
$contact_name = "Name: ".$yourname;
$message_text = "Message: ".$yourmessage;
$user_answer = trim(htmlspecialchars($_POST['user_answer']));
$answer = trim(htmlspecialchars($_POST['answer']));
$message = $contact_name . $return . $message_text;
$headers = "From: ".$youremail;
if (email_is_valid($youremail) && !eregi("\r",$youremail) && !eregi("\n",$youremail) && $yourname != "" && $yourmessage != "" && substr(md5($user_answer),5,10) === $answer) {
mail($to,$subject,$message,$headers);
$yourname = '';
$youremail = '';
$yourmessage = '';
echo '<p style="color: blue;">'.$contact_submitted.'</p>';
}
else echo '<p style="color: red;">Please enter your name, a valid email address, your message and the answer to the simple maths question before sending your message.</p>';
}
$number_1 = rand(1, 9);
$number_2 = rand(1, 9);
$answer = substr(md5($number_1+$number_2),5,10);
?>
<form id="contact" action="contact.php" method="post">
<div class="form_settings">
<p><span>Name</span><input class="contact" type="text" name="your_name" value="<?php echo $yourname; ?>" /></p>
<p><span>Email Address</span><input class="contact" type="text" name="your_email" value="<?php echo $youremail; ?>" /></p>
<p><span>Message</span><textarea class="contact textarea" rows="5" cols="50" name="your_message"><?php echo $yourmessage; ?></textarea></p>
<p style="line-height: 1.7em;">To help prevent spam, please enter the answer to this question:</p>
<p><span><?php echo $number_1; ?> + <?php echo $number_2; ?> = ?</span><input type="text" name="user_answer" /><input type="hidden" name="answer" value="<?php echo $answer; ?>" /></p>
<p style="padding-top: 15px"><span> </span><input class="submit" type="submit" name="contact_submitted" value="send" /></p>
</div>
</form>`
Can somebody help me? The error I get: http://i50.tinypic.com/2hfpe7m.jpg.
The fact that PHP commands are showing in your page clearly indicate that PHP is either not installed, or not properly configure. Make sure that it is up and running, and that your file has a .php extension.
Also your source code is missing the opening <?php. It might only be missing from your question, but make sure it is present in your file.
You're missing the opening PHP tag.
Simply add:
<?php
At the top of the script.

Categories