Example Form

This is an example PHP form that processes user information, checks for errors, and validates the captcha code.
This example form also demonstrates how to submit a form to itself to display error messages.

Name*:

Email*:

URL:

Message*:

'ct_captcha')); ?>


$value) { if (!is_array($key)) { // sanitize the input data if ($key != 'ct_message') $value = strip_tags($value); $_POST[$key] = htmlspecialchars(stripslashes(trim($value))); } } $name = @$_POST['ct_name']; // name from the form $email = @$_POST['ct_email']; // email from the form $URL = @$_POST['ct_URL']; // url from the form $message = @$_POST['ct_message']; // the message from the form $captcha = @$_POST['ct_captcha']; // the user's entry for the captcha code $name = substr($name, 0, 64); // limit name to 64 characters $errors = array(); // initialize empty error array if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) { // only check for errors if the form is not in debug mode if (strlen($name) < 3) { // name too short, add error $errors['name_error'] = 'Your name is required'; } if (strlen($email) == 0) { // no email address given $errors['email_error'] = 'Email address is required'; } else if ( !preg_match('/^(?:[\w\d-]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/i', $email)) { // invalid email format $errors['email_error'] = 'Email address entered is invalid'; } if (strlen($message) < 20) { // message length too short $errors['message_error'] = 'Please enter a message'; } } // Only try to validate the captcha if the form has no errors // This is especially important for ajax calls if (sizeof($errors) == 0) { require_once dirname(__FILE__) . '/securimage.php'; $securimage = new Securimage(); if ($securimage->check($captcha) == false) { $errors['captcha_error'] = 'Incorrect security code entered'; } } if (sizeof($errors) == 0) { // no errors, send the form $time = date('r'); $message = "A message was submitted from the contact form. The following information was provided.

" . "Name: $name
" . "Email: $email
" . "URL: $URL
" . "Message:
" . "
$message
" . "

IP Address: {$_SERVER['REMOTE_ADDR']}
" . "Time: $time
" . "Browser: " . htmlspecialchars($_SERVER['HTTP_USER_AGENT']) . "
"; if (isset($GLOBALS['DEBUG_MODE']) && $GLOBALS['DEBUG_MODE'] == false) { // send the message with mail() mail($GLOBALS['ct_recipient'], $GLOBALS['ct_msg_subject'], $message, "From: {$GLOBALS['ct_recipient']}\r\nReply-To: {$email}\r\nContent-type: text/html; charset=ISO-8859-1\r\nMIME-Version: 1.0"); } $return = array('error' => 0, 'message' => 'OK'); die(json_encode($return)); } else { $errmsg = ''; foreach($errors as $key => $error) { // set up error messages to display with each field $errmsg .= " - {$error}\n"; } $return = array('error' => 1, 'message' => $errmsg); die(json_encode($return)); } } // POST } // function process_si_contact_form()