i'm using a simple contact form on my website using PHP, and i'm about to install SSL on my website, codewise do i need to make any changes to the PHP code, i'm totaly new to SSL and this is my first SSL installation .
<?php
$errors = array();
$missing = array();
if (isset($_POST['send'])) {
$to = 'john#example.com';
$subject = 'Feedback from contact form';
$expected = array('name', 'email', 'comments');
$required = array('name', 'email', 'comments');
$headers = "From: webmaster#example.com\r\n";
$headers .= "Content-type: text/plain; charset=utf-8";
require './includes/mail_process.php';
if ($mailSent) {
header('Location: thanks.php');
exit;
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Contact Us</title>
<link href="./styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Contact Us</h1>
<?php if ($_POST && $suspect) { ?>
<p class="warning">Sorry your mail could not be be sent.</p>
<?php } elseif ($errors || $missing) { ?>
<p class="warning">Please fix the item(s) indicated.</p>
<?php }?>
<form name="contact" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
<label for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span>
<?php } ?>
</label>
<input type="text" name="name" id="name"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email address</span>
<?php } elseif (isset($errors['email'])) { ?>
<span class="warning">Invalid email address</span>
<?php } ?>
</label>
<input type="text" name="email" id="email"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span class="warning">You forgot to add your comments</span>
<?php } ?>
</label>
<textarea name="comments" id="comments"><?php
if ($errors || $missing) {
echo htmlentities($comments, ENT_COMPAT, 'utf-8');
}
?></textarea>
</p>
<p>
<input type="submit" name="send" id="send" value="Send Comments">
</p>
</form>
<pre>
</body>
</html>
the mail_process.php goes like this
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
$$key = '';
} elseif(in_array($key, $expected)) {
$$key = $temp;
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-to: $validemail";
} else {
$errors['email'] = true;
}
}
if (!$suspect && !$missing && !$errors) {
$message = '';
foreach ($expected as $item) {
if (isset($$item) && !empty($$item)) {
$val = $$item;
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item) . ": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers, $authenticate);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
Since you don't have any absolute URL references you won't have a problem. I'd recommend you put this in your header (or at the top of all your PHP files) to force them to use https, that way if you did need absolute URLs in your website, you can have them all HTTPS as everyone would be forced there anyway.
if($_SERVER['HTTPS'] != 'on' || !stristr($_SERVER['HTTP_HOST'], 'www.')) {
$redirect= "https://www.".str_replace('www.','',$_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI'];
header("Location:$redirect");
}
You would have to change absolute URL's to "https://....". If you are not using absolute URL's there is nothing to change if your form and processing script are both on https.
Related
I've gone through and read a bunch of other questions asked about this issue, but I'm still as confused now as when I started with this problem. From what I have read, I've learned the following:
I don't believe any html is being done before the header() - But I'm new at this still so I'm possibly wrong.
I haven't found any syntax errors.
The form submits ok and I receive test emails.
What happens is, I fill out the form completely with valid text and hit Submit. The data is submitted and sent to my email and the page refreshes back to a fresh contact form (contact.php) where it should be instead going to my thanks.php page.
Here is my code, email addresses changed.
Thank you in advance for any/all help! Much appreciated.
<?php
$errors = array();
$missing = array();
if (isset($_POST['send'])) {
$to = 'My Name <rawr#test.com>';
$subject = 'Feedback from Contact Form';
$expected = array('name', 'email', 'comments');
$required = array('name', 'email', 'comments');
$headers = "From: admin#website.com\r\n";
$headers .= "Content-Type: text/plain; charset=utf-8";
$authenticate = null;
if ($mailSent) {
header('Location: thanks.php');
exit();
}
}
include './navigation.php';
?>
<?php
//mail process **Don't Touch**
$suspect = false;
$pattern = '/Content-Type:|Bcc:|CC:/i';
function isSuspect ($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
$$key = '';
} elseif(in_array($key, $expected)) {
$$key = $temp;
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-to: $validemail";
} else {
$errors['email'] = true;
}
}
if (!$suspect && !$missing && !$errors) {
$message = '';
foreach ($expected as $item) {
if (isset($$item) && !empty($$item)) {
$val = $$item;
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item) . ": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers, $authenticate);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
//end mail process
?>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Contact Carla <3</title>
<link href="/design.css" rel="stylesheet" type="text/css"/>
</head>
<body id="contact">
<div id="main">
<?php if (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))) { ?>
<span class="warning">Sorry your mail could not be sent.</span>
<?php } elseif ($errors || $missing) { ?>
<span class="warning">Please fix the item(s) indicated.</span>
<?php } ?>
<form name="contact" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
<label for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span class="warning">Who am I responding to?</span>
<?php } ?>
</label>
<br>
<input type="text" name="name" id="name"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span class="warning">How will I respond to you?</span>
<?php } elseif (isset($errors['email'])) { ?>
<span class="warning">Invalid email address</span>
<?php } ?>
</label>
<br>
<input type="text" name="email" id="email"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span class="warning">Please say something..</span>
<?php } ?>
</label>
<br>
<textarea rows="7" cols="70" name="comments" id="comments"><?php
if ($errors || $missing) {
echo htmlentities($comments, ENT_COMPAT, 'utf-8');
}
?></textarea>
</p>
<p>
<input type="submit" name="send" id="send" value="Send Comments">
</p>
</form>
</div>
</body>
<?php include './footer.php'; ?>
</html>
Your problem is this line
if ($mailSent) {
header('Location: thanks.php');
exit();
}
You have not set $mailsent anywhere above that statement. So it is never getting to that point.
Once it has passed that part of your code it will not pop back up to check if mail sent unless you call a function or similar down lower that points to it.
I hope that sets you on the right path, let me know if you need further help.
First time poster, be gentle.
I have a form with a .php processing script that worked fine for the longest time except for the fact that I started to receive spam. I did some research on Captcha's and came across Securimage which was (supposedly) one of the easiest to implement. I downloaded the files and installed it into my script. I came across two problems.
The form was still sending if the captcha was left blank (it still notified me that it was blank).
The form was still sending if the captcha was wrong (it still notified me that it was wrong).
You can see it in action here: http://216.119.71.44/contact/
I "patched" issue 1 just by making the field a required field. I need some help fixing number 2. Below is my code and you can find the documentation for securimage here:
contact.php:
<?php
$thisPage = "Contact";
$errors = array();
$missing = array();
$date = date('F j, Y');
// check if the form has been submitted
if (isset($_POST['send'])) {
// sends the message to recipient
ini_set("SMTP","mail.abcprintingink.com");
// Please specify an SMTP Number 25 and 8889 are valid SMTP Ports.
ini_set("smtp_port","587");
// Please specify the return address to use
$to = 'paulr#abcprintingink.com'; //recipient's email address
$from = $_POST['email']; // this is the sender's Email address
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$subject = 'Online Form Submission';
$expected = array('fname','lname','email','phone','comments','captcha_code');
$required = array('fname','lname','email','phone','comments','captcha_code','');
$headers = "From: Technical Staffing Solutions";
// sends a copy of the message to the sender
$receiptHeader = "From: Technical Staffing Solutions";
$receiptSubject = "Copy of your form submission";
$receipt = "Hello " . $fname . "," . "\n" . "Below is a copy of the message you sent to us on " . $date . ". We will contact you as soon as possible. Thank you!" . "\n\n" . $_POST['comments'];
mail($from,$receiptSubject,$receipt,$receiptHeader);
// detailed processing script (checks for errors)
require('../include/processmail.php');
}
?>
<h1>CONTACT US</h1>
<?php
// Various on submit mail messages
if ($mailSent) {
echo "<div id=\"form-success\"><div>✓</div><p>Thank you " . $fname . ", your message has been sent.</p></div>";
}
elseif (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))) {
echo "<div id=\"form-error\"><div>!</div><p>Your message could not be sent. Please try again.</p></div>";
}
elseif ($missing || $errors) {
echo "<div id=\"form-error\"><div>!</div><p>Please fill out the required fields and try again.</p></div>";
}
?>
<form id="getquote" method="post" action="" style="float:left;">
<input type="text" id="fname" name="fname" placeholder="First Name"
<?php if ($missing && in_array('fname', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($fname, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="text" id="lname" name="lname" placeholder="Last Name"
<?php if ($missing && in_array('lname', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($lname, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="email" id="email" name="email" placeholder="Email Address"
<?php if ($missing && in_array('email', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<input type="text" id="phone" name="phone" placeholder="Phone Number"
<?php if ($missing && in_array('phone', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($phone, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<textarea placeholder="How can I help you?" id="comments" name="comments"
<?php if ($missing && in_array('comments', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($comments, ENT_COMPAT, 'UTF-8') . '"'; } ?>> </textarea><br>
<!-- Captcha -->
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
↻
<input type="text" id="captcha_code" name="captcha_code" size="10" maxlength="6"
<?php if ($missing && in_array('captcha_code', $missing)) { ?>style="border: 1px solid #cc0000;"
<?php } if ($missing || $errors) { echo 'value="' . htmlentities($captcha_code, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
<!-- Submit -->
<div style="width:292px;"><input type="submit" id="send" name="send" value="SUBMIT"></div>
</form>
processmail.php:
<?php
session_start();
$suspect = false; //assume nothing is suspect
$pattern = '/Content-Type:|Bcc:|Cc:/i'; //create a pattern to locate suspect phrases
function isSuspect($val, $pattern, &$suspect) { //function to check for suspect phrases
if (is_array($val)) { //if the variable is an array, loop thorugh each element and pass it recursively back to the same function
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if(preg_match($pattern, $val)) {
$suspect = true;
}
}
}
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value); //assign to temporary variable and strip whitespace if not an array
if (empty($temp) && in_array($key, $required)) { //if empty and requires, add to $missing array
$missing[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp; //otherwise, assign to a variable of the same name as $key
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-To: $validemail";
} else {
$errors['email'] = true;
}
}
$mailSent = false;
if (!$suspect && !$missing && !$errors) { //go ahead only if not suspect and all required fields are ok
$message = "";
foreach($expected as $item) { //loop through the $expected array
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val = 'Not Selected'; //if it has no value, assign 'not selected'
}
if (is_array($val)) { //if an array, expand as comma-separated string
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item); //replace underscores and hyphens in the label with spaces
$message .= ucfirst($item).": $val\r\n\r\n"; //add label and value to the message body
}
$message = wordwrap($message, 70); //limit the line length to 70 characters
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
I am new to PHP and I have problem to select values which have space between for eg TRANSGENDER FtM, if I use TRANSGENDER-MtF then am able to save it. And same with name input, here is the code:
<?php
include_once 'core/init.php';
$general->logged_out_protect();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css" >
<title>Settings</title>
</head>
<body>
<div class="nav-bar" style="box-shadow:0 0 5px 0 rgba(0, 0, 0, 0.4);" >
<?php include 'includes/menu.php'; ?>
</div><!-- NAV BAR DIV closes here -->
<div id="main-wrap" style=" box-shadow:0 0 5px 0 rgba(0, 0, 0, 0.4);">
<div id="container">
<?php
if (isset($_GET['success']) && empty($_GET['success'])) {
echo '<h3>Your details have been updated!</h3>';
} else{
if(empty($_POST) === false) {
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
if (ctype_alpha($_POST['first_name']) === false) {
$errors[] = 'Please enter your First Name with only letters!';
}
}
if (isset($_POST['last_name']) && !empty ($_POST['last_name'])){
if (ctype_alpha($_POST['last_name']) === false) {
$errors[] = 'Please enter your Last Name with only letters!';
}
}
if (isset($_POST['gender']) && !empty($_POST['gender'])) {
$allowed_gender = array('undisclosed', 'Male', 'Female');
if (in_array($_POST['gender'], $allowed_gender) === false) {
$errors[] = 'Please choose a Gender from the list';
}
}
if (isset($_POST['trans']) && empty($_POST['trans'])) {
$allowed_trans = array(
"--Undisclosed--",
"Transperson",
"Transgender",
"Transsexual MtF",
"Transsexual FtM",
"Transvestite MtF",
"Transvestite FtM",
"Intergender",
"Intersexual");
if (in_array($_POST['trans'], $allowed_trans) === false) {
$errors[] = 'Please choose a Trans from the list if Any';
}
}
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name'])) {
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif' );
$a = explode('.', $name);
$file_ext = strtolower(end($a)); unset($a);
$file_size = $_FILES['myfile']['size'];
$path = "avatars";
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Image file type not allowed';
}
if ($file_size > 2097152) {
$errors[] = 'File size must be under 2mb';
}
} else {
$newpath = $user['image_location'];
}
if(empty($errors) === true) {
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']['name']) && $_POST['use_default'] != 'on') {
$newpath = $general->file_newpath($path, $name);
move_uploaded_file($tmp_name, $newpath);
}else if(isset($_POST['use_default']) && $_POST['use_default'] === 'on'){
$newpath = 'avatars/default_avatar.png';
}
$first_name = htmlentities(trim($_POST['first_name']));
$last_name = htmlentities(trim($_POST['last_name']));
$gender = htmlentities(trim($_POST['gender']));
$bio = htmlentities(trim($_POST['bio']));
$trans = htmlentities(trim($_POST['trans']));
$image_location = htmlentities(trim($newpath));
$users->update_user($first_name, $last_name, $gender, $bio, $image_location, $user_id, $trans);
header('Location: settings.php?success');
exit();
} else if (empty($errors) === false) {
echo '<p>' . implode('</p><p>', $errors) . '</p>';
}
}
?>
<h2>Settings.</h2> <p><b>Note: Information you post here is made viewable to others.</b></p>
<hr />
<form action="" method="post" enctype="multipart/form-data">
<div id="profile_picture">
<h3>Change Profile Picture</h3>
<ul>
<?php
if(!empty ($user['image_location'])) {
$image = $user['image_location'];
echo "<img src='$image'>";
}
?>
<li>
<input type="file" name="myfile" />
</li>
<?php if($image != 'avatars/default_avatar.png'){ ?>
<li>
<input type="checkbox" name="use_default" id="use_default" /> <label for="use_default">Use default picture</label>
</li>
<?php
}
?>
</ul>
</div>
<div id="personal_info">
<h3 >Change Profile Information </h3>
<ul>
<li>
<h4>First name:</h4>
<input type="text" name="first_name" value="<?php if (isset($_POST['first_name']) ){echo htmlentities(strip_tags($_POST['first_name']));} else { echo $user['first_name']; }?>">
</li>
<li>
<h4>Last name: </h4>
<input type="text" name="last_name" value="<?php if (isset($_POST['last_name']) ){echo htmlentities(strip_tags($_POST['last_name']));} else { echo $user['last_name']; }?>">
</li>
<li>
<h4>Gender:</h4>
<?php
$gender = $user['gender'];
$options = array("undisclosed", "Male", "Female");
echo '<select name="gender">';
foreach($options as $option){
if($gender == $option){
$sel = 'selected="selected"';
}else{
$sel='';
}
echo '<option '. $sel .'>' . $option . '</option>';
}
?>
</select>
</li><br>
<li>
<h4>Trans:</h4>
<?php
$trans = $user['trans'];
$options = array("--Undisclosed--",
"Transperson",
"Transgender",
"Transsexual MtF",
"Transsexual FtM",
"Transvestite MtF",
"Transvestite FtM",
"Intergender",
"Intersexual");
echo '<select name="trans">';
foreach($options as $option){
if($trans == $option){
$sel = 'selected="selected"';
}else{
$sel="";
}
echo '<option '. $sel .'>' . $option . '</option>';
}
?>
</select>
</li><br>
<li>
<h4>Bio:</h4>
<textarea name="bio"><?php if (isset($_POST['bio']) ){echo htmlentities(strip_tags($_POST['bio']));} else { echo $user['bio']; }?></textarea>
</li>
</ul>
</div>
<div class="clear"></div>
<hr />
<span>Update Changes:</span>
<input type="submit" value="Update">
</form>
</div><!-- Container DIV closes here -->
</div><!-- Main Wrap DIV closes here -->
</body>
</html>
<?php
}
In relation to your screenshot, the problem is that your validation on "First name" is working correctly! I would first suggest that in order to make this change, you should change the form to read "First name(s):" to make it clear that any number of first names are allowed in this field. Ideally you should do this with the field name too.
Your code is thus:
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
if (ctype_alpha($_POST['first_name']) === false) {
$errors[] = 'Please enter your First Name with only letters!';
}
}
The function your code uses is ctype_alpha, which does not permit spaces. You could change this to:
if (isset($_POST['first_name']) && !empty ($_POST['first_name'])){
// Remove spaces from intermediate variable, to permit them
$firstNames = str_replace(' ', '', $_POST['first_name']);
if (ctype_alpha($firstNames) === false) {
$errors[] = 'Please enter your first name(s) with only letters!';
}
}
I have a one page website. Each menu item scrolls you to a different part of the page. I have a HTML and PHP form which reloads the page and displays an error message if the form is submitted with a required field not filled. The problem is it reloads to the top of the page whereas my form is at the bottom of the page.
How can I get the form to reload the page to the section where the contact form is? The form already does exactly that when the form is submitted successfully but not when there are errors.
Any help would be great. Thanks for reading.
HTML
<div id="contactBox">
<form name="contact" id="contactForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id="formLeft">
<p>
<label for="name">Name</label>
<?php if ($missing && in_array('name', $missing)) { ?>
<div class="warningDivLeft">
<span class="warning">Please enter your name</span>
</div>
<?php } ?>
<input type="text" name="name" id="name" tabindex="10"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="company">Company Name/Website</label>
<input type="text" name="company" id="company" tabindex="30"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($company, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="email">Email</label>
<?php if ($missing && in_array('email', $missing)) { ?>
<div class="warningDivLeft">
<span class="warning">Please enter your email</span>
</div>
<?php } elseif (isset($errors['email'])) { ?>
<div class="warningDivLeft">
<span class="warning">Invalid email address</span>
</div>
<?php } ?>
<input type="email" name="email" id="email" tabindex="40"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" tabindex="50"
<?php
if ($errors || $missing) {
echo 'value="' . htmlentities($phone, ENT_COMPAT, 'utf-8') . '"';
}
?>
>
</p>
<p>
<label for="contactYou">Contact you by...</label>
<?php if ($missing && in_array('contactYou', $missing)) { ?>
<div class="warningDivLeft">
<span class="warning">Please select one</span>
</div>
<?php } ?>
<select name="contactYou" size="1" id="contactYou" tabindex="60">
<option value="" selected="selected">- select</option>
<option value="email" <?php echo ($contactYou == 'email') ? ' selected="selected"' : ''; ?>>Email</option>
<option value="phone" <?php echo ($contactYou == 'phone') ? ' selected="selected"' : ''; ?>>Phone</option>
</select>
</p>
</div>
<div id="formRight">
<p>
<label for="interest">I am interested in...</label>
<?php if ($missing && in_array('interest', $missing)) { ?>
<div class="warningDiv">
<span class="warning">Please select one</span>
</div>
<?php } ?>
<select name="interest" size="1" id="interest" tabindex="80">
<option value="" selected="selected">- select</option>
<option value="new" <?php echo ($interest == 'new') ? ' selected="selected"' : ''; ?>>Creating a new website</option>
<option value="current" <?php echo ($interest == 'current') ? ' selected="selected"' : ''; ?>>Redesigning a current website</option>
<option value="responsive" <?php echo ($interest == 'responsive') ? ' selected="selected"' : ''; ?>>Reponsive web design</option>
<option value="wordpress" <?php echo ($interest == 'wordpress') ? ' selected="selected"' : ''; ?>>A WordPress website</option>
<option value="general" <?php echo ($interest == 'general') ? ' selected="selected"' : ''; ?>>General enquiry</option>
</select>
</p>
<p>
<label for="budget">My budget is...</label>
<?php if ($missing && in_array('budget', $missing)) { ?>
<div class="warningDiv">
<span class="warning">Please select one</span>
</div>
<?php } ?>
<select name="budget" size="1" id="budget" tabindex="90">
<option value="" selected="selected">- select</option>
<option value="100" <?php echo ($budget == '100') ? ' selected="selected"' : ''; ?>>€100 - €500</option>
<option value="500" <?php echo ($budget == '500') ? ' selected="selected"' : ''; ?>>€500 - €1,000</option>
<option value="1000" <?php echo ($budget == '1000') ? ' selected="selected"' : ''; ?>>€1,000 - €2,000</option>
<option value="2000" <?php echo ($budget == '2000') ? ' selected="selected"' : ''; ?>>€2,000 - €5,000</option>
<option value="5000" <?php echo ($budget == '5000') ? ' selected="selected"' : ''; ?>>€5,000 - €10,000</option>
<option value="10000" <?php echo ($budget == '10000') ? ' selected="selected"' : ''; ?>>€10,000+</option>
</select>
</p>
<p>
<label for="comments">How can I help you?</label>
<?php if ($missing && in_array('comments', $missing)) { ?>
<div class="warningDiv">
<span class="warning">Please leave a comment</span>
</div>
<?php } ?>
<textarea name="comments" id="comments" cols="45" rows="5" tabindex="100"><?php
if ($errors || $missing) {
echo htmlentities($comments, ENT_COMPAT, 'utf-8');
}
?></textarea>
</p>
</div>
<div id="formSubmit">
<ul>
<li>
<input type="submit" name="submit" id="submit" value="Send Message" tabindex="70">
</li>
</ul>
</div>
</form>
PHP
<?php
$errors = array();
$missing = array();
if (isset($_POST['submit'])) {
$to = 'celinehalpin#hotmail.com';
$subject = 'Web Design';
$expected = array('name', 'company', 'email', 'phone', 'contactYou', 'interest', 'budget', 'comments');
$required = array('name', 'email', 'contactYou', 'interest', 'budget', 'comments');
$headers = "From: webmaster#example.com\r\n";
$headers .= "Content-type: text/plain; charset=utf-8";
$authenticate = '-fcelinehalpin#hotmail.com';
require './_includes/mail_process.php';
if ($mailSent) {
header('Location: ' . $_SERVER['REQUEST_URI'] . '?success=1#c');
exit;
}
}
?>
<?php if (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))) { ?>
<div class="globalWarning">
<p class="warning">Sorry your mail could not be sent</p>
</div>
<?php } elseif ($errors || $missing) { ?>
<div class="globalWarning">
<p class="warning">Please fix the item(s) indicated</p>
</div>
<?php } elseif (isset($_GET['success'])) { ?>
<div class="globalAlert">
<p class="warning">Thank you! Your message has been sent!</p>
</div>
<?php } ?>
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
$$key = '';
} elseif(in_array($key, $expected)) {
$$key = $temp;
}
}
}
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-to: $validemail";
} else {
$errors['email'] = true;
}
}
if (!$suspect && !$missing && !$errors) {
$message = '';
foreach ($expected as $item) {
if (isset($$item) && !empty($$item)) {
$val = $$item;
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item) . ": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers, $authenticate);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
It sounds like what you need is some Javascript to do the scrolling. I don't know if you're using jQuery or not, but it makes this fairly easy. This Stack Overflow link describes a number of approaches to it, such as:
$.fn.scrollView = function () {
return this.each(function () {
$('html, body').animate({
scrollTop: $(this).offset().top
}, 1000);
});
}
and calling it like:
$('#your-form').scrollView();
In addition to that, you might want to consider seeing if you can do any input validation BEFORE the form is submitted. Check out HTML5's input patterns and required fields
I would put some javascript within your error php so that when that loads it runs the javascript thus scrolling to the correct location based on form ID
DEMO http://jsfiddle.net/RbxVJ/2/
$(function() {
$(document).scrollTop( $("#header").offset().top );
});
Actually I would use pure javascript as you may not have called the jQuery library at this point
EDITED
Your PHP
DEMO http://jsfiddle.net/RbxVJ/430/
<?php
if(!isset($_GET['success']))
{
?>
<script>
window.location.hash = '#your-form-ID';
</script>
<?php
}
?>
If you are going to be using JavaScript to solve the problem, you might as well use it to validate your form rather/in addition to PHP. It is quicker (avoiding the necessary refresh with PHP), and you should never find yourself in the position to have to reload the form in any way other than with a successful submission.
Write a function that executes when the submit button is pressed that gathers the required fields, checks them for appropriate values, stops form submission if any are missing, and then, alters the HTML with reminder text next to those that 'broke the rules' as it were.
$(document).ready(function(){
$('#contactBox a[href="' + window.location.hash + '"]').click();
});
I was having a similar issue. When the form on the current page was submitted I would reload the current page. My form was at the bottom of the page, but when the page was reloaded the page would be scrolled to the very top again. Reloading the current page is done with;
<form action="">
So if my form is on my index.html page, this is the same as;
<form action="index.html">
To solve the scrolling issue I gave the form element an id and then referenced this id in the 'action' attribute value, like so;
<form id="contact-form" action="#contact-form">
Again if the form is on my index.html page, this is the same as;
<form id="contact-form" action="index.html#contact-form">
If you weren't aware, when you append an element id to the end of the web page URL, it will load that web page and scroll directly to that element.
If there are any concerns with this method please chime in.
I've been learning PHP via the book "PHP Solutions" by David Powers, which has a contact form with basic validation/error handling and input sanitization I would like to use without refreshing the page.
I'm testing this locally with XAMPP, and using the php form itself works perfectly: error messages display correctly, and if the form is successfully submitted, a thank you page is displayed and the form is delivered as an email to my test email address.
Now I need the form to submit and display error messages with AJAX. I've read many posts on accomplishing this, but I've been unsuccessful in implementing this. I've tried both the jQuery $.ajax and $.post methods - if the fields are all filled, the success message displays, but the message is not sent.
My guess is that javascript and php arrays are structured differently, but don't know how to reconcile this. I'm not even sure what the php processing scripts are getting/sending, if anything. How can I get this form to submit without refreshing the page, but still using the php scripts for server-side validation?
To simplify, I've stripped everything else from my page (and put all files in the same folder), except for the form: php, html, and the jQuery/AJAX I can't figure out.
Hope this makes sense. My 4 files:
mySite.js (the jQuery/AJAX I'm having trouble with...):
mySite = {
jsFormSubmission : function() {
$("#feedback").submit(function(event){
event.preventDefault();
var errorMsg = "<p class=\"errorBox\">Please fix the item(s) indicated.</p>";
var successMsg = "<p class=\"messageBox\">Thanks for the submission, your message has been sent.</p>";
var myObject = {
name : $("#name").val(),
email : $("#email").val(),
comments : $("#comments").val()
};
var ajaxData = JSON.stringify(myObject);
$.ajax({
type: 'POST',
url: 'form.php',
data: ajaxData,
success: function(data){
$(".formResult").html(successMsg);
},
error: function(http) {
$(".formResult").html(errorMsg);
alert(http.responseText);
}
});
});
}
};
The form (contact.php):
<?php include("form.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src=" mySite.js"></script>
<script type="text/javascript">
$(document).ready(function() {
mySite.jsFormSubmission();
});
</script>
</head>
<body>
<div id="contact">
<p class="formResult"></p>
<?php $errorForm = (($_POST && $suspect) || ($_POST && isset($errors['mailfail'])));
$errorTag = $missing || $errors;
if ($errorForm || $errorTag) { ?>
<p class="errorBox">
<?php } ?>
<?php if ($errorForm) { ?>
Sorry, your message could not be sent. Please try again later.
<?php } elseif ($errorTag) { ?>
Please fix the item(s) indicated.
<?php } ?>
<?php if ($errorForm || $errorTag) { ?>
</p>
<?php } ?>
<form id="feedback" method="post" action="">
<div class="tag">
<label id="lblName" for="name">Name:
<?php if ($missing && in_array('name', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your name</span>
<?php } ?>
</label>
<input name="name" id="name" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblEmail" for="email">Email:
<?php if ($missing && in_array('email', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your email address</span>
<?php } elseif (isset($errors['email'])) { ?>
<span style="color:red; font-weight:bold;">Invalid email address</span>
<?php } ?>
</label>
<input name="email" id="email" type="text" class="formbox"
<?php if ($missing || $errors) {
echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"';
} ?>>
</div>
<div class="tag">
<label id="lblComments" for="comments">Comments:
<?php if ($missing && in_array('comments', $missing)) { ?>
<span style="color:red; font-weight:bold;">Please enter your message</span>
<?php } ?>
</label>
<textarea name="comments" id="comments" cols="60" rows="8"><?php
if ($missing || $errors) {
echo htmlentities($comments, ENT_COMPAT, 'UTF-8');
} ?></textarea>
</div>
<p>
<input name="send" id="send" type="submit" value="Send message">
</p>
</form>
</div>
</body>
</html>
form.php (included at top of contact.php):
<?php
$name = '';
$email = '';
$comments = '';
$required = '';
$errors = array();
$missing = array();
// check if the form has been submitted
if (isset($_POST['send'])) {
//email processing script
$to = 'johntest2#localhost';
$subject = 'Website contact form';
//list expected fields
$expected = array('name', 'email', 'comments');
// set required fields
$required = array('name', 'email', 'comments');
$headers = "From: Website Contact Test<johntest1#localhost>\r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
require('processmail.php');
if ($mailSent) {
header("Location: thankYou.php#main");
$messageConfirm = true;
exit;
}
}
?>
processmail.php (validation scripts - included in form.php):
<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';
// function to check for suspect phrases
function isSuspect($val, $pattern, &$suspect) {
if (is_array($val)) {
foreach ($val as $item) {
isSuspect($item, $pattern, $suspect);
}
} else {
if (preg_match($pattern, $val)) {
$suspect = true;
}
}
}
isSuspect($_POST, $pattern, $suspect);
if (!$suspect) {
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
} elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
}
// validate the user's email
if (!$suspect && !empty($email)) {
$validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($validemail) {
$headers .= "\r\nReply-To: $validemail";
} else {
$errors['email'] = true;
}
}
$mailSent = false;
if (!$suspect && !$missing && !$errors) {
// initialize the $message variable
$message = '';
foreach($expected as $item) {
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val = 'Not selected';
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item).": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
$mailSent = mail($to, $subject, $message, $headers);
if (!$mailSent) {
$errors['mailfail'] = true;
}
}
There's a few ways that you can get the error to display from the PHP side. You can throw an exception, which I wouldn't recommend, or use a header:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
In your AJAX call, use the jQuery error callback:
$.ajax({
url: //url,
data: //data,
success: function (data) { //show success },
error: function () { //display code here }
});
You can also return the error in the body of the error message from the PHP side, and strip that from the body in your error callback.
PHP:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo 'Your error message';
JavaScript:
error: function(http) {
// show http.responseText;
}
Also, for your form submission, pack your data into a object, and then serialize it. So:
var myObject = {
property1 : 'string',
property2 : [ 'array' ]
};
var ajaxData = JSON.stringify(myObject);