PHP articles and tutorials
- Dynamic navigation list
- Safe Ajax contact form
- Horizontal Navigation
- More will come soon...
Post your comments here
A (safe) contact form using Xajax and PHPmailer
Providing a simple contact form could be a big security issue if the form script doesn't have any validation or security features. In the past it was very common to use simple mail scripts to post a web form to some e-mail address. A lot of the spam getting people in their mail box is send with vulnerable form mail scripts.
Using Xajax
For those people thinking Ajax is a Dutch Soccer club, I must say they are right! But Ajax is more, we are using in this tutorial Xajax a very powefull and easy to use PHP Class library which makes it possible to execute a PHP script using XML and some JavaScript code. Get the latest Xajax library here.
Sending mails with PHPMailer
PHPMailer is very popular PHP mail script with a lot of possebilities: Send mails via SMTP, sendmail, Qmail or the with PHP mail function. The class is able to handle multiple attachments and can be used for full featured e-mail clients, download the class here.
We have created a demo to show how the form does looks like.
OK, lets start... first we need to include the class files for phpmailer and Xajax, note in this tutorial are all files located in one folder. The class file folders are one level above:
require_once('xajax/xajax.inc.php');
Because we want to hide the contact form after the mail is send we need to store the html inside a variable to make it dynamic. Note the form name cform and the javascript event inside the button form field xajax_myFunction(xajax.getFormValues('cform')). The last one is the user event we need later to process the form.
<div>
<label for="name">Name</label>
<input name="name" type="text" id="naam" value="" size="25" />
</div>
<div>
<label for="email">E-mail</label>
<input name="email" type="text" id="email" value="" size="25" />
</div>
<div>
<label for="msg">Message</label>
<textarea name="msg" id="msg" cols="45" rows="5"></textarea>
</div>
<div style="border-top:1px solid #CCCCCC;padding-top:5px;">
<label for="subbtn" style="text-align:right;"> --> </label>
<input type="button" id="subbtn" value="Submit" onclick="xajax_myFunction(xajax.getFormValues('cform'));" />
</div>
</form>';
Now we have to build the function which has to be executed if the user hits the submit button. The function has the following parts:
- Create a new Xajax response object
- Form field validation (e-mail address validation), if not valid the user gets a message
- Creating the PHPMailer object and define the required vars for the e-mail task
- Sending the mail message...
- the response (replace the form with some message) is send to the browser
global $form, $error;
$error = '';
$objResponse = new xajaxResponse();
$show_form = true;
if (!empty($get['email']) && !empty($get['msg']) && !empty($get['name'])) {
if (preg_match("/^[\w-]+(\.[\w-]+)*@([0-9a-z][0-9a-z-]*[0-9a-z]\.)+([a-z]{2,4})$/i", trim($get['email']))) {
$email = preg_replace("/\r\n/", "", $get['email']);
$from = preg_replace("/\r\n/", "", $get['name']);
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.yourserver.com";
$mail->SMTPAuth = true;
$mail->Username = "postmaster@yourserver.com";
$mail->Password = "password";
$mail->From = "postmaster@yourserver.com";
$mail->FromName = "Webmaster";
$mail->AddAddress("admin@yourserver.com");
$mail->AddReplyTo($email, $from);
$mail->Subject = "contact form using Xajax and phpmailer";
$mail->Body = $get['msg'];
if ($mail->Send()) {
$error = "The form is submitted and the mail is send.";
$show_form = false;
} else {
$error = "There was a problem while sending the mail, please try again";
}
} else {
$error = "The entered e-mail address is not valid.";
}
} else {
$error = "At least one of the fields is empty...";
}
$data = (!$show_form) ? '<p class="contactMsg">'.$error.'</p>' : '<p class="contactMsg">'.$error.'</p>'.$form;
$objResponse->addAssign('contact_result', 'innerHTML', $data);
return $objResponse;
}
After the e-mail is send, the form inside the element with the ID contact_result is replaced with some message using JavaScript innerHTML function
How to use the code inside a webpage?
Place the form (variable), the function (and the includes) before of all html code. Next we need to include some JavaScript file in the documents HTML header:
Inside the documents body we need to place this code: (note the name myFunction used as argument for the registerFunction method)
$xajax = new xajax();
$xajax->registerFunction('myFunction');
$xajax->processRequests();
echo '<div id="contact_result">'.$form.'</div>';
?>
That's all, a simple but safe contact form. There is more, because we used some fancy Ajax feature the page doesn't need to be reloaded to get the information that the e-mail is send and double submissions are not possible because the form button is hidden after submission.