AJAX engine
custom rolled AJAX with field collection, SHA-1 client-side encryption and PHP 5 on server-side.
PHP 5 procedural.
Front-End
front-end, hand-rolled, AJAX engine for multiple form processing for one website.
var engine;
function ajaxRequest(page){
engine=buildEngine();
if( engine==null ){
alert( "Your browser does not support AJAX. This could be due to having JavaScript disabled or because your browser is outdated." );
return;
}
var str=getStr(page);
var url="../include/ajax.engine.php?"+str+"&sid="+Math.random();
engine.onreadystatechange=stateChanged;
engine.open("GET",url,true);
engine.send(null);
}
function stateChanged(){
if( engine.readyState==4 || engine.readyState=="complete" )
document.getElementById("ajaxReturn").innerHTML=engine.responseText;
else
document.getElementById("ajaxReturn").innerHTML='<p>You request is being processed.</p><img src="../images/site/ajaxLoader.gif" />';
}
function buildEngine(){
var engine=null;
try{ engine=new XMLHttpRequest(); }
catch(e){
try{ engine=new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e){ engine=new ActiveXObject("Microsoft.XMLHTTP"); }
}
return engine;
}
function getStr(page){ // page can either be "booking","contact", or "register"
switch (page) {
case "booking":
var fields = ["name","company","location","email","remail","phone","phoneExt","description"];
var _form=document.forms.booking);
break;
case "contact":
var fields = ["name","subject","email","remail","message"];
var _form=document.forms.contact);
break;
case "register":
var fields = ["name","username","pw1","pw2","email","remail","comments"];
var _form = document.forms.registration);
}
return getFormData(page, fields, _form);
}
function getFormData(page, fields, _form) {
var result="", data="";
for( var i=0; i<fields.length; i++ ){
if( fields[i]=="pw1" || fields[i]=="pw2" )
data=encodeURI(hex_sha1(_form[fields[i]].value)); // encrypt passwords client side SHA-1
else data=encodeURI(_form[fields[i]].value);
if( i==0 )
result="page="+page+"&"+fields[i]+"="+data;
else result+="&"+fields[i]+"="+data;
}
return result;
Back-End
This script validates and processes all AJAX requests for a PHP site.
<?php require_once('db.php'); session_start();
if( $_GET['page']=="booking" ){
$vars=array("name","company","location","email","remail","phone","phoneExt","description");
foreach( $vars as $value ){ $_SESSION[$value]=$_GET[$value]; }
validateName(); validateCompany(); validateLocation();
validateEmail(); validatePhone(); validatePhoneExt(); validateDescription();
// everything checks out, run code...
sendBookingRequest();
}
elseif( $_GET['page']=="contact" ){
$vars=array("name","subject","email","remail","message");
foreach( $vars as $value ){ $_SESSION[$value]=$_GET[$value]; }
validateName(); validateSubject(); validateEmail(); validateMessage();
// everything checks out, run code...
sendContactRequest();
}
elseif( $_GET['page']=="register" ){
$vars=array("name","username","pw1","pw2","email","remail","comments");
foreach( $vars as $value ){ $_SESSION[$value]=$_GET[$value]; }
validateName(); validateUN(); validatePW(); validateEmail(); validateComments();
// everything checks out, run code...
sendRegRequest();
}
else {
echo( 'Something went wrong. Your request did not match any of the available options. Please contact the site webmaster in the <a href="'.$_SERVER['HTTP_HOST'].'/contact">contact</a> section."' );
}
/*_______________________________________________________ SUB FUNCTIONS
*/
//____________________________________BOOKING
function sendBookingRequest()
{
$to = 'email@domain.com';
$from = $_GET['email'];
$subject = '>>Booking request [request ID: '.rand(1,80000).']';
$message = '<html>
<head><title>JV Booking</title></head>
<body>
<h3>'.$_GET['name'].' from company ('.$_GET['company'].') located in '.$_GET['location'].' says</h3>
<p>'.$_GET['description'].'</p>
<h3>Phone #: '.$_GET['phone'].'<br />Ext: '.$_GET['phoneExt'].'</h3>
</body>
</html>';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: First LastName <email@domain.com>' . "\r\n";
$headers .= 'From: JV Booking - '.$_GET['name'].' <'.$_GET['email'].'>' . "\r\n";
if( mail($to, $subject, $message, $headers ) )
echo('<p>Thank you '.$_GET['name'].'. Your request has been sent. I will reply as soon as I receive it.</p><p><strong>Job Description</strong></p><p>'.$_GET['description'].'</p>');
else echo('Could not send message');
}
//____________________________________CONTACT
function sendContactRequest()
{
$to = 'email@domain.com';
$subject = '>>'.$_GET['subject'].' [contact ID: '.rand(1,80000).']';
$message = '<html>
<head>
<title>JV Email Contact</title>
</head>
<body>
<p>'.$_GET['message'].'</p>
</body>
</html>';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Name <email@domain.com>' . "\r\n";
$headers .= 'From: '.$_GET['email'] . "\r\n";
$headers .= 'Reply-To: '.$_GET['email'] . "\r\n";
if( mail($to, $subject, $message, $headers) )
echo( '<h3>Your message has been sent.</h3><p>I will reply as soon as I read it.' );
else echo( '<p>Could not send message</p>' );
}
//____________________________________REGISTRATION
function sendRegRequest()
{ global $mysqli;
$name=$mysqli->real_escape_string($_GET['name']);
$un=$mysqli->real_escape_string($_GET['username']);
$encryptUn=sha1($un);
$pw=stripslashes($_GET['pw1']);
$date=date("Y-m-d");
$email=$mysqli->real_escape_string($_GET['email']);
$comments=$mysqli->real_escape_string($_GET['comments']);
// Check if user has already registered
$chkIfUserExists="SELECT MemRealName, MemUN, MemEmail FROM Members WHERE MemRealname='$name' OR MemUN='$un' OR MemEmail='$email'";
if( $result=$mysqli->query($chkIfUserExists) ){
if( $result->num_rows == 1 ){
error( 'You have already registered for this site. If your registration has been recent, please await confirmation.
If your registration has been pending for some time, please contact Jessica in the <a href="../contact">contact</a> section.
Thank you for your interest in JessicaVilanova dotcom.' );
}
}
// User is not registered, so send mail application, and add them to the database w/ status "pending"...
if( sendRegMailRequest($name, $un, $encryptUn, $pw, $date, $email, $comments) ){
$insertMemberPending="INSERT INTO Members(MemRealName,MemUN,MemUNEncrypted,MemPW,MemDateJoined,MemEmail,MemStatus) VALUES ('$name','$un','$encryptUn','$pw','$date','$email','pending')";
if( $result=$mysqli->query($insertMemberPending) ){
echo( "You request for membership has been sent. When your request is recieved it will either be approved or denied. Thank you for your interest in jessicavilanova.com" );
}
} else error( 'Something went wrong. This could be do to an incorrect email address ('.$_GET['email'].'). Please try a different email address. If this problem persists, please contact the webmaster in the <a href="'.$_SERVER['HTTP_HOST'].'/contact">contact section</a>. Thank you for your interest in JessicaVilanova dotcom.' );
}
function sendRegMailRequest($name, $un, $encryptUn, $pw, $date, $email, $comments)
{
$to = 'email@domain.com';
$subject = '>>New Membership request [random request ID: '.rand(1,80000).']';
$message = '<html>
<head>
<title>New Membership Request</title>
</head>
<body>
<h3>The following person has requested membership to your site:</h3>
<strong>Name: </strong> : '.$name.'<br />
<strong>Username: </strong> : '.$un.'<br />
<strong>Email: </strong> : '.$email.'<br />
<h3>Comments</h3>
<p>'.$comments.'</p>
<h2>To approve this application please <a href="'.$_SERVER['HTTP_HOST'].'/include/member.approve.php?name='.$name.'&un='.$un.'&encryptUn='.$encryptUn.'&pw='.$pw.'&date='.$date.'&email='.$email.'">click here</a></h2>
<h2>To deny this application please <a href="'.$_SERVER['HTTP_HOST'].'/include/member.deny.php?name='.$name.'&un='.$un.'&encryptUn='.$encryptUn.'&pw='.$pw.'&date='.$date.'&email='.$email.'">click here</a></h2>
<p>Do NOT reply to this email Jess! Just click either APPROVE or DENY.</p>
</body>
</html>';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Name <email@domain.com>' . "\r\n";
$headers .= 'From: '.$_GET['email'] . "\r\n";
$headers .= 'Reply-To: '.$_GET['email'] . "\r\n";
if( mail($to, $subject, $message, $headers) ) return true;
else return false;
}
/*_______________________________________________________ VALIDATION FUNCTIONS
*/
function validateName(){
if( isset($_GET['name']) && $_GET['name'] != "" ){
if( strlen($_GET['name']) < 4 ) error('Name must be longer than 3 characters.');
if( strlen($_GET['name']) > 255 ) error('Name cannot be more than 255 characters long.');
} else error('You must provide a name.');
}
function validateUN(){
if( isset($_GET['username']) && $_GET['username'] != "" ){
if( strlen($_GET['username']) < 8 ||
strlen($_GET['username']) > 16 || !ereg("^[[:alpha:]][[:alpha:][:digit:]_]*$", $_GET['username']) ){
error('Username must start with a letter, contain only letters, numbers, underscores, and be between 8 and 16 characters long.');
}
} else error('You must provide a username.');
}
function validatePW(){
if( isset($_GET['pw1']) && isset($_GET['pw2']) ){
if( $_GET['pw1']!= $_GET['pw2'] ) error('Passwords did not match.');
if( $_GET['pw1']=="da39a3ee5e6b4b0d3255bfef95601890afd80709" || $_GET['pw2']=="da39a3ee5e6b4b0d3255bfef95601890afd80709" )
error('You must provide a password, both password fields must match.');
} else error('You must provide a password.');
}
function validateEmail(){
if( isset($_GET['email']) && isset($_GET['remail']) ){
if( $_GET['email']==$_GET['remail'] ){
if( !eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$', $_GET['email']) ){
error('Email must be in format \'name@domain.com\'. I.e. webmaster@jessicavilanova.com');
}
} else error('Emails did not match.');
} else error('You must provide both email address fields.');
}
function validateSubject(){
if( !isset($_GET['subject']) || $_GET['subject'] == "" ){
error('Subject must be provided.');
}
if( strlen($_GET['subject']) > 500 ){
error('Subject can not be longer than 500 characters.');
}
}
function validateComments(){
if( isset($_GET['comments']) ){
if( strlen($_GET['comments']) > 1000 ){
error('Comments can not be over 1,000 characters.');
}
} else $comments="no comments";
}
function validateCompany(){
if( isset($_GET['company']) ){
if( strlen($_GET['company']) > 400 ){
error('Company name can not be over 400 characters long.');
}
} else $company="no company";
}
function validateLocation(){
if( !isset($_GET['location']) ){
error('You must provide a location.');
}
}
function validatePhone(){
if( isset($_GET['phone']) ){
$phone=preg_replace('/[^0-9]/', '', $_GET['phone']); # remove non-numbers
if( !preg_match('/^1?[0-9]{10}$/', $phone)) {
error('Phone number must be provided in one of the following formats; <br /> (555)555-5555<br />555-555-5555<br />555 555 5555');
}
}
}
function validatePhoneExt(){
if( !isset($_GET['phoneExt']) || $_GET['phoneExt'] == "" ){
return;
}
elseif( isset($_GET['phoneExt']) ){
if( strlen($_GET['phoneExt']) > 4 ){
error('Phone Extension can not be longer than 4 numbers.');
}
if( strlen($_GET['phoneExt']) < 1 ){
error('Phone Extension can not be shorter than 1 number.');
}
}
}
function validateDescription(){
if( isset($_GET['description']) ){
if( !isset($_GET['description']) ){
error('Please provide a description of your job/project.');
}
} else error('Please provide a description of your job/project.');
}
function validateMessage(){
if( !isset($_GET['message']) || $_GET['message'] == "" ){
error('You must provide a message.');
}
}
function error($error){
exit( '<h3>The following error needs correcting:</h3>'.$error.'<br /><a href="./"> click here to correct this error.</a>' );
}
?>













