It would be safer anyways, as you should have it validating on the server side no matter what.
Always remember. Server-side validation (PHP) is mandatory, as its sure to work no matter what, and is your main script; using client-side validation (JavaScript) is only a convenience for the user.
Now that I remember, I do use AJAX myself to validate the code, but it is when it is actually sent to the server, so it isn't fully client-side. It simply submits the entire form to my script with AJAX, then the script validates it against the session data, and if it doesn't match, it replies with a special flag, that tells my AJAX handler to run a reset function, which alerts the user that the security code was incorrect, saves the form data onto a temporary session value, and then completely refreshes the page. My page then has the form able to grab that session data if it exists, and puts it back into the form.
Here's a simple example. (Uses the
Prototype Library)
JavaScript
/* Sendmail Object */
var Sendmail = {
// AJAX Send Email
Send: function(){
if(!checkform('contact')) return false;
var opt = {
method:'post',
postBody: Form.serialize('contact_form'),
onSuccess: function(t) { Sendmail.HandleSend(t); },
onLoading: function() { $('submit').value = 'Sending...'; $('submit').disabled = true; $('response').innerHTML = '<img src="/images/icons/loading.gif" alt="Loading... Please Wait" />'; }
}
new Ajax.Request('/ajax/sendmail.php', opt);
},
// Handle Send Email
HandleSend: function(t){
data = t.responseText.split('|');
if(data[0] == 1) $('submit').value = 'Message Sent!';
else if(data[0] == -1){
alert(data[1]);
reset_contact();
}
else{
$('submit').value = 'Submit';
$('submit').disabled = false;
}
$('form_response').innerHTML = data[1];
}
}
Contact Page
<?php
// Grab Previous Form Data
$form = isset($_SESSION['contact_form']) ? unserialize($_SESSION['contact_form']) : array();
function getdata($data){
global $form;
echo htmlspecialchars($form[$data]);
}
?>
<div class="box">
<h2><span style="font-size:10px;">÷</span> Contact Us</h2>
<p>Please use this form to contact us concerning anything.</p>
</div>
<br /><br />
<form id="contact_form" name="contact_form" action="/contact.php" method="post" onsubmit="return false;">
<h2>Contact Form</h2>
<table cellpadding="5" cellspacing="0" style="text-align:center;margin:0 auto;width:100%;">
<tr>
<td><strong>Subject:</strong></td>
<td><input id="contact_subject" type="text" name="contact_subject" maxlength="255" style="width:280px;" value="<?php getdata('subject'); ?>" /></td>
</tr>
<tr>
<td><strong>Name:</strong></td>
<td><input id="contact_name" type="text" name="contact_name" maxlength="15" style="width:280px;" value="<?php getdata('name'); ?>" /></td>
</tr>
<tr>
<td><strong>Email Address:</strong></td>
<td><input id="contact_email" type="text" name="contact_email" maxlength="255" style="width:280px;" value="<?php getdata('email'); ?>" /></td>
</tr>
<tr>
<td><strong>Message:</strong></td>
<td><textarea id="message" name="message" style="width:280px;" rows="10" cols="10"><?php getdata('message'); ?></textarea></td>
</tr>
<tr>
<td>
<strong>Security Code:</strong><br />
<img src="/lib/security_image.php" alt="Security Image" title="Please enter this code into the input field to the right." /><br /><a href="java script:reset_contact();">Cannot see image?</a>
</td>
<td><input id="security_image" type="text" name="security_image" maxlength="5" style="width:200px;" /></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" id="submit" name="submit" onclick="Sendmail.Send();" value="Submit" /> <input type="reset" onclick="return reset_form('contact_form')" value="Reset" /></td>
</tr>
</table>
</form>
<div id="form_response"> </div>
AJAX Handling File
<?php
// Cleaning Functions
// Strip HTML Function
function strip_html($data){
$search = array('@<script[^>]*?>.*?</script>@si', // Strip Javascript
'@<style[^>]*?>.*?</style>@siU', // Strip Style Tags
'@<[\/\!]*?[^<>]*?>@si', // Strip HTML tags
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip Multi-line Comments (CDATA)
);
return preg_replace($search, '', $data);
}
// Clean User Data Function
function cleandata($data){
return trim(htmlspecialchars(strip_html($data)));
}
// Send Email
if(!$_POST['submit'])
$message_error['Invalid Data'] = 'The information you have submitted does not appear to have been correctly submitted by our form. If you recieve this error after correctly filling out our form, please contact us through another method.';
if($_SERVER['REQUEST_METHOD'] != 'POST')
$message_error['Unauthorized Access'] = 'This page has been accessed through an unauthorized method. Please go back and submit through the form correctly.';
// Retrieve Form Variables
$subject = SITE_NAME.': '.cleandata($_POST['contact_subject']);
$name = cleandata($_POST['contact_name']);
$email = cleandata($_POST['contact_email']);
$message = cleandata($_POST['message']);
$headers = 'From: '.SITE_NAME.' <'.EMAIL_FEEDBACK.">\nReply-To: {$name} <{$email}>\n";
if(strtolower($_POST['security_image']) != strtolower($_SESSION['gen_key'])){
$_SESSION['contact_form'] = serialize('subject' => $subject, 'name' => $name, 'email' => $email, 'message' =>$message);
if($ajax)
echo "-1|Invalid Security Code\n\nSorry, but the code you entered does not match the image. Please try again."
else
echo '<div class="box"><h2><span style="font-size:10px;">÷</span> Error!</h2><p class="error"><strong>Message Error:</strong> <span class="red">Invalid Security Code</span><br /><span class="indent">Sorry, but the code you entered does not match the image. Please try again.</span></p></div>';
return;
}
else
unset($_SESSION['contact_form'], $_COOKIE['contact_form'], $_SESSION['gen_key']);
// Ensure No Blank Fields
if(is_type('empty', $subject, $name, $email, $message))
$message_error['Missing Information'] = 'It appears you did not fill the entire form out. Please make sure all required fields are filled out correctly and try again.';
// Regex Validate Email
if(!preg_match('#([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9-]+)(\.[a-z]{2,3})?)#i', $email))
$message_error['Invalid Email'] = 'The email submitted does not appear to be a correct email. Please check your email address and try again.';
// Exploits Validate Email
if(preg_match('#(content-type|bcc:|cc:|document.cookie|onclick|onload)#i', $email))
$message_error['Exploit Found'] = 'The email submitted appears to contain exploits. Please check your email address and try again.';
// Exploits Validate Message
if(preg_match('#(content-type|bcc:|cc:|document.cookie|onclick|onload)#i', $message))
$message_error['Exploit Found'] = 'The message submitted appears to contain exploits. Please check your message and try again.';
// Name Length Validate
if(strlen($name) > 15)
$message_error['Name Length Exceeds Limit'] = 'The name submitted is longer than 15 characters. Please check your name and try again.';
// Name Character Validate
if(!preg_match('#([A-Za-z\' -]*)#i', $name))
$message_error['Invalid Name'] = 'The name submitted contains special characters. Please remove any special characters and try again.';
$message = 'This e-mail has been sent by '.SITE_NAME.' <'.SITE_URL.">\n\nMessage Details:\nIP Address: {$_SERVER['REMOTE_ADDR']}\nBrowser: {$_SERVER['HTTP_USER_AGENT']}\nE-Mail Time:".formatDate(date('Y-m-d H:i:s'))."\n\n\nMessage:\n".$message;
if(empty($message_error)){
// Send Message
if(@mail(EMAIL_ADMIN, $subject, $message, $headers))
// Echo Success
echo '1|<div class="box"><h2><span style="font-size:10px;">÷</span> Thank You!</h2><p>Your message has been recieved.</p></div>';
else
// Echo Error
$message_error['Error Sending Mail'] = 'An unknown error has occured while trying to send your email. This may be a problem on our end. Please try again, or contact us via messanger about this problem.';
}
if(!empty($message_error)){
$return = '<div class="box"><h2><span style="font-size:10px;">÷</span> Error!</h2>';
foreach($message_error as $k => $v) $return .= "<p class=\"error\"><strong>Message Error:</strong> <span class=\"red\">{$k}</span><br /><span class=\"indent\">{$v}</span></p>\n";
echo '0|'.$return.'</div><br />';
}
?>
Has some stuff in there specific to the site I am building, such as the cleandata() function, but that should show you a very secure way of validating your data incase you haven't already implicated such things.
Edited by Demonslay, 05 May 2007 - 11:48 AM.