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);
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;
}
Link to website: http://www.leonardpfautsch.com/contact.php
How do I make my contact form validated only using PHP? I want to be able to have error messages directly under the text field that has an error. For each text field, I do not want multiple errors to show up at once. If you submit the form with nothing in the fields, you see that under name and email two errors show up for each. I want the errors to show up only once due to some type of specifications. Right now I think I am on the right track. However, the code below does not have the email being sent. I am very new to PHP. If anybody could help me, I would really appreciate it.
<?php
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (!empty($_POST['action']))){
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if ($name === '') {
$name_error_1 = '<div style="color:red;"> Name is a required field! </div>';
}
if ($email === '') {
$email_error_1 = '<div style="color:red;"> Email is a required field! </div>';
}
if ($subject === '') {
$subject_error = '<div style="color:red;"> Subject is a required field! </div>';
}
if ($message === '') {
$message_error = '<div style="color:red;"> Message is a required field! </div>';
}
if (isset($email) && (filter_var($email, FILTER_VALIDATE_EMAIL) === false)){
$email_error_2 = '<div style="color:red;"> The email address must be real! </div>';
}
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
/*Main way that mail works*/
if (empty($errors) === true) {
/*Where_mail_goes_to, Subject, Body_text, Who_email_is_from*/
mail('email_address', $subject, "From " . $name . "\r\r" . $message, 'From: ' . $email);
/*Shows up in the URL if the message has been sent*/
header('Location: contact.php?sent');
exit();
}
} //end of main if
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>" >
<span class="label">Name</span><br/>
<?php if (isset($name_error_1)) { echo $name_error_1; } ?>
<?php if (isset($name_error_2)) { echo $name_error_2; } ?>
<input type="text" class="textfield" name="name" size="50" maxlength="50" <?php if (isset($_POST['name']) === true) { echo 'value="', strip_tags($_POST['name']), '"'; } ?> > <br/>
<span class="label">Email</span><br/>
<?php if (isset($email_error_1)) { echo $email_error_1; } ?>
<?php if (isset($email_error_2)) { echo $email_error_2; } ?>
<input type="text" class="textfield" name="email" size="50" maxlength="50" <?php if (isset($_POST['email']) === true) { echo 'value="', strip_tags($_POST['email']), '"'; } ?> > <br/>
<span class="label">Subject</span><br/>
<?php if (isset($subject_error)) { echo $subject_error; } ?>
<input type="text" class="textfield" name="subject" size="50" maxlength="50" <?php if (isset($_POST['subject']) === true) { echo 'value="', strip_tags($_POST['subject']), '"'; } ?> > <br/>
<span class="label">Message</span><br/>
<?php if (isset($message_error)) { echo $message_error; } ?>
<textarea rows="5" cols="50" name="message" id="textarea" maxlength="500"><?php if (isset($_POST['message']) === true){ echo $_POST['message'];}?></textarea><br/>
<input type="submit" value="Send" id="submit" name="action">
</form>
You could create an array of errors for each field and display just the first error added to it.
<?php
$email_errors = array();
if ($email == '')
{
$email_errors[] = 'First error';
}
if (more_email_checks($email) == false)
{
$email_errors[] = 'Second error';
}
?>
...
<span class="label">Email</span><br />
<?php echo array_shift($email_errors); ?>
To know whether to send e-mails or not, you could do something like this:
$errors_found = 0;
if (check_email($email) == false)
{
$email_error = 'Error message';
$errors_found++;
}
...
if ($errors_found == 0)
{
mail(...);
}
You can do it by using the elseif check
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}
elseif(isset($email_error_2)) {
echo $email_error_2;
} ?>
Also move this line after the last validation check
if (ctype_alpha($name) === false) {
$name_error_2 = '<div style="color:red;"> Your name must only contain letters! </div>';
}
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
you can by this code for name
<?
$message = "<div style = 'color :red ' /> ;
if (isset(name == '' ) {
echo $message
}
?>
this is name php vaildation but yo can create js
Change your email validation to:
<span class="label">Email</span><br/>
<?php if (isset($email_error_1))
{
echo $email_error_1;
}else if(isset($email_error_2)) {
echo $email_error_2;
} ?>
same if else can be applied to all the fields with multiple validation conditions.
and then move your error array just above the email condition check:
<?php
$errors = array($name_error_1, $name_error_2, $email_error_1, $email_error_2, $subject_error, $message_error);
//and change your mail function as:
$to = 'email_address';
$headers = $headers .= 'From: $name <$email>';
mail($to, $subject, $message, $headers);
?>
Also perform a check on the control, if you have filled the form completely then it should come to the mail function, I mean just check the if condition, in case you have some issue with the condition, try to put an echo inside if statement(which is responsible for sending email), and if that echo statement executes then mail should work.
:)
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.
I have a registration form that I want to validate using jQuery and than pass it to PHP to login if all details are correct.
I am trying to use Yendesigns form - http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/
My form code is:
<?php
require_once("includes/initialise.php");
if (isset($_POST['resetpassword']) && $_POST['resetpassword'] == 'resetnow') {
$required = array('first_name','last_name','username','email','password','password2');
$missing = array();
$validation = array(
'first_name' => 'Please provide your first name',
'last_name' => 'Please provide your last name',
'username' => 'Please provide your username',
'email' => 'Please provide your valid email address',
'password' => 'Please provide your password',
'password2' => 'Please confirm your password',
'userdup' => 'Username already registered',
'emaildup' => 'Email address already registered',
'mismatch' => 'Passwords do not match'
);
//Sanitise and clean function
$first_name = escape($_POST['first_name']);
$last_name = escape($_POST['last_name']);
$username = escape($_POST['username']);
$email = escape($_POST['email']);
$password = escape($_POST['password']);
$password2 = escape($_POST['password2']);
foreach($_POST as $key => $value) {
$value = trim($value);
if(empty($value) && in_array($key,$required)) {
array_push($missing,$key);
} else {
${$key} = escape($value);
}
}
if($_POST['email'] !="" && getDuplicate(1,'email','clients','email',$email)) {
array_push($missing,'emaildup');
}
if($_POST['username'] !="" && getDuplicate(1,'username','clients','username',$username)) {
array_push($missing,'userdup');
}
// Check User Passwords
if( strcmp($_POST['password'], $_POST['password2']) != 0 ) {
array_push($missing,'mismatch');
}
//validate email address
if(!empty($_POST['email']) && !isEmail($_POST['email'])) {
array_push($missing,'email');
}
if(!empty($missing)) {
$before = " <span class=\"errorred\">";
$after = "</span>";
foreach($missing as $item)
${"valid_".$item} = $before.$validation[$item].$after;
} else {
// stores MD5 of password
$passmd5 = md5($_POST['password']);
// stores clients IP addresss
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$date = date('Y-m-d');
$time = date('H:i:s');
// Generates activation code simple 4 digit number
$hash = mt_rand().date('YmdHis').mt_rand();
//Insert Data
$sql = "INSERT INTO clients(first_name, last_name, username, email, password, date, time, `hash`)
VALUES ('{$first_name}','{$last_name}','{$username}','{$email}','$passmd5','$date', '$time','$hash')";
$result = mysql_query($sql, $conndb) or die(mysql_error());
if($result) {
$to = $_POST['email'];
$subject = 'Activate your account';
$from = 'dummy#emailaddress.co.uk';
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type:text/html;charset=UTF-8\r\n";
$headers .= "From: My Website Name <".$from.">\r\n";
$headers .= "Reply-to: My Website Name <".$from.">\r\n";
$message = '<div style="font-family:Arial, Verdana, Sans-serif; color:#333; font-size:12px">
<p>Thank you for registering on our website</p>
<p>Please click on the following link to activate your account:
http://'.$host.''.$path.'/activate.php?id='.$hash.'</p>
<p>Here are your login details...</p>
<p>User Name: '.$username.'</p>
<p>Email: '.$email.' </p>
<p>Passwd: '.$password.' </p>
</p></div>';
if (mail($to, $subject, $message, $headers)) {
$confirmation = '<p>Thank you.<br />You have successfully registered.</p>';
} else {
$confirmation = '<p>Error.<br />Your activation link could not be sent.<br />Please contact administrator.</p>';
}
}
}
}
require_once("includes/header.php");
?>
<div class="block">
<div class="block_head">
<div class="bheadl"></div>
<div class="bheadr"></div>
<h5>Register</h5>
<ul>
<li>Login</li>
</ul>
</div> <!-- .block_head ends -->
<div class="block_content">
<?php echo isset($confirmation) ? $confirmation : NULL; ?>
<form name="register" id="customForm" action="" method="post">
<div>
<label for="first_name">First Name: * <?php echo isset($valid_first_name) ? $valid_first_name : NULL; ?></label>
<input id="first_name" name="first_name" type="text" class="fld" value="" />
<span id="first_nameInfo"></span>
</div>
<div>
<label for="last_name">Last Name: * <?php echo isset($valid_last_name) ? $valid_last_name : NULL; ?></label>
<input id="last_name" name="last_name" type="text" class="fld" value="" />
<span id="last_nameInfo"></span>
</div>
<div>
<label for="username">Username: * <?php echo isset($valid_username) ? $valid_username : NULL; ?> <?php if(isset($valid_userdup)) { echo $valid_userdup; } ?></label>
<input id="username" name="username" type="text" class="fld" value="" />
<span id="usernameInfo"></span><span id="status"></span>
</div>
<div>
<label for="email">E-mail: * <?php if(isset($valid_email)) { echo $valid_email; } ?> <?php if(isset($valid_emaildup)) { echo $valid_emaildup; } ?></label>
<input id="email" name="email" type="text" class="fld" value="" />
<span id="emailInfo"></span>
</div>
<div>
<label for="pass1">Password: * <?php if(isset($valid_password)) { echo $valid_password; } ?></label>
<input id="pass1" name="pass1" type="password" class="fld" value="" />
<span id="pass1Info"></span>
</div>
<div>
<label for="pass2">Confirm Password: * <?php if(isset($valid_password2)) { echo $valid_password2; } ?> <?php if(isset($valid_mismatch)) { echo $valid_mismatch; } ?></label>
<input id="pass2" name="pass2" type="password" class="fld" value="" />
<span id="pass2Info"></span>
</div>
<div>
<input id="send" name="send" type="submit" value="Send" />
</div>
</table>
<input type="hidden" name="resetpassword" value="resetnow" />
</form>
</div>
<!-- .block_content ends -->
<div class="bendl"></div>
<div class="bendr"></div>
</div>
<?php
require_once("includes/footer.php");
?>
And the jquery is:
/***************************/
//#Author: Adrian "yEnS" Mato Gondelle & Ivan Guardado Castro
//#website: www.yensdesign.com
//#email: yensamg#gmail.com
//#license: Feel free to use it, but keep this credits please!
/***************************/
$(document).ready(function(){
//global vars
var form = $("#customForm");
var first_name = $("#first_name");
var first_nameInfo = $("#first_nameInfo");
var last_name = $("#last_name");
var last_nameInfo = $("#last_nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var pass1 = $("#pass1");
var pass1Info = $("#pass1Info");
var pass2 = $("#pass2");
var pass2Info = $("#pass2Info");
var message = $("#message");
//On blur
first_name.blur(validateName);
last_name.blur(validateLastName);
email.blur(validateEmail);
pass1.blur(validatePass1);
pass2.blur(validatePass2);
//On key press
first_name.keyup(validateName);
last_name.keyup(validateLastName);
pass1.keyup(validatePass1);
pass2.keyup(validatePass2);
message.keyup(validateMessage);
//On Submitting
form.submit(function(){
if(validateName() & validateLastName() & validateEmail() & validatePass1() & validatePass2() & validateMessage())
return true
else
return false;
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Please provide a valid email address");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(first_name.val().length < 4){
first_name.addClass("error");
first_nameInfo.text("Please provide your first name (more than 3 letters)");
first_nameInfo.addClass("error");
return false;
}
//if it's valid
else{
first_name.removeClass("error");
first_nameInfo.text("");
first_nameInfo.removeClass("error");
return true;
}
}
function validateLastName(){
//if it's NOT valid
if(last_name.val().length < 4){
last_name.addClass("error");
last_nameInfo.text("Please provide your first name (more than 3 letters)");
last_nameInfo.addClass("error");
return false;
}
//if it's valid
else{
last_name.removeClass("error");
last_nameInfo.text("");
last_nameInfo.removeClass("error");
return true;
}
}
function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Please provide your password (at least 5 characters)");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("");
pass2Info.removeClass("error");
return true;
}
}
function validateMessage(){
//it's NOT valid
if(message.val().length < 10){
message.addClass("error");
return false;
}
//it's valid
else{
message.removeClass("error");
return true;
}
}
});
When I click the submit button the form passes via php and stops the jquery. If the submit button is not pressed than it carries on validating via jQuery.
How can I get it to if all details are correct to pass the PHP validation too. If errors or user has jQuery disabled to validate via PHP?
Thank you
A good web application has two layers of validation:
The input is validated client side with javascript (e.g. jquery). It gives better feedback for the user if the validation is done immediately without contacting the server.
The input is validated server side to guard against malicious users having bypassed the client side validation (or simply a user with javascript disabled). There are also cases where validation rules are hard to implement client side.
If you want to test your server side validation, the easiest is probably to temporary disable javascript in the browser.
METHOD 1: In your jQuery (untested):
$("#send").click(function(e) {
e.preventDefault();
// call javascript validation functions here
// if valid then submit form:
$("#customForm").submit();
});
EDIT: If user has not got javascript, then the form will be submitted as usual and validated by php only when the submit button is clicked. But if javascript is enabled, then the default submit action will be prevented, and you can first check whatever you want to check on the client side before submitting the form.
METHOD 2: Instead of the jQuery code above, you can instead call your javascript validation functions with an onSubmit="return validate();" form attribute, where validate() javascript function returns false if there are errors. This will also prevent the form from submitting directly - unless the user does not have javascript.
UPDATE IN RESPONSE TO ZAFER's COMMENT:
In method 1, might be better to use this instead:
$("#customForm").submit(function(e) {
e.preventDefault();
// call javascript validation functions here
// if valid then submit form:
$(this).submit();
});
to insert into a database i use this function.
/**
* Takes an array or string and takes out malicous code.
* #param array|string $var
* #param string $key
* #return string
*/
function aspam($var, $returnZero = false, $key = '') {
if (is_array($var) && !empty($key)) {
/*
* if var is array and key is set, use aspam on the array[key]
* if not set, return 0 or ''
*/
if (isset($var[$key])) {
return general::aspam($var[$key], $returnZero);
} else {
return ($returnZero) ? 0 : '';
}
} elseif (is_array($var) && empty($key)) {
/*
* if var is array and key is empty iterate through all the members
* of the array and aspam the arrays and take out malicous code of the
* strings or integers.
*/
$newVar = array();
$newVal = '';
foreach ($var as $key => $val) {
if (is_array($val)) {
$newVal = general::aspam($val, $returnZero);
} elseif (!empty($val)) {
$newVal = trim(htmlspecialchars($val, ENT_QUOTES));
} else {
$newVal = ($returnZero) ? 0 : '';
}
$newVar[$key] = $newVal;
}
return $newVar;
} elseif (!empty($var)) {
/*
* Strip malicous code
*/
return trim(htmlspecialchars($var, ENT_QUOTES));
} else {
/*
* return default 0 | '' if string was empty
*/
return ($returnZero) ? 0 : '';
}
}
to use this function you put in the array, then tell it if you want to return empty or 0.
$product_id = aspam($_REQUEST, true, 'product_id');
The javascript with jquery you can itterate through a class and validate all at once.
/*variable to check if it is valid*/
var returnVar = true;
$('.required').each(function () {
if ($(this).is("select")) {
if ($(this).val() > '0') {
/*Code for is valid*/
$(this).parent().removeClass("alert-danger");
} else {
/*Code for is not valid*/
$(this).parent().addClass("alert-danger");
returnVar = false;
}
} else {
if (!$(this).val()) {
/*Code for is valid*/
$(this).parent().addClass("alert-danger");
returnVar = false;
} else {
/*Code for is not valid*/
$(this).parent().removeClass("alert-danger");
}
}
});
if(returnVar){
/*submit form*/
}