Can anyone reccomend me a good secure PHP/Mailto form tutorial

Soldato
Joined
1 Dec 2004
Posts
23,076
Location
S.Wales
There are lots of these on the web, but the only problem is they are either simple (non-secure) ones, or ones that claim to be secure but are not fully secure.

I would like a reccomendation on one that will tacle

Form input validation
Prevent PHP Injections
Prevent spam attacks?

So far I have only written the top part of my sendmail.php file as im researching on the web for the best methods to use

Code:
/Sendmail.php copyright dmoranda.co.uk 2009
//-------------------------------------------

<?php

//SQL Database Connection

$host='***';
$username='***';
$password='***';
$db_name='***';
$tbl_name='***';
	
mysql_connect($host, $username, $password)or die('cannot connect');
mysql_select_db($db_name)or die('cannot select DB');


//Variable declarations
	$name = strip_tags($_POST['name']);
	$email = strip_tags($_POST['email']);
	$message = strip_tags($_POST['message']);
 
Input validation: Never done this myself as my forms never have enough submissions to warrant it. Only thing I can think that you'd need this for would be email address, in which case a simple 'string includes an @' and 'last 3 characters include a .' should do the job.

PHP Injections: Looks like you're taking the first steps there anyway. Someone will hopefully post a link to a site made by a guy from OcUK explaining how to take further steps.

Spam attacks: Captchas. You can either use a ready-built one (recaptcha.net) or make your own. I always prefer the latter as I make the words in the image relative to the site (simple case of typing the text and using Ripple effect or similar in PS) and that's enough to stop bots. Here's a bit of code that might help:

Code:
[B]Form[/B]
X = Last captcha image number

<?$captchanum = rand(1,X);?>
<img src="../images/captcha<?echo $captchanum?>.jpg"><br>Type the word above*<br>
<input name="captchaword" type="text" class="form" size="35" value="">
<input name="captchanum" type="hidden" class="form" size="35" value='<?echo $captchanum?>'><br><br>


[B]PHP[/B]
$captchawords = array("word1", "word2", "word3", "word4");
$captchanumbers = array("1", "2", "3", "4");
$captchaconverted = str_replace($captchawords, $captchanumbers, $captchaword);
if($captchaconverted != $captchanum){

Hope that helps somewhat :)
 
Last edited:
Why do you need a database for mailto form? Standard PHP contact form doesn't require a database as its just getting POST data and using the mail() function to send out an email using your web hosting.
 
Why do you need a database for mailto form? Standard PHP contact form doesn't require a database as its just getting POST data and using the mail() function to send out an email using your web hosting.

Custom visitor tracker perhaps? I use that anyway, ie all visitors routes into and through my site are logged as well as any interaction such as whether they made contact via a form or checked a date etc. Helps work out which the best referrers are as well as what individual pages are working well and which aren't.
 
OK, so im guessing there isnt really any great need for me to use a database backend for this? all i want is a secure one :)
 
hi, here is my php form submit code:

PHP:
<?php
if (!isset($_POST['submit']) || $_SERVER['REQUEST_METHOD'] != "POST") {
    exit("<p>This page should not be access directly</p>");
} else {
    $exploits = "/(content-type|bcc:|cc:|document.cookie|onclick|onload|javascript|alert)/i";
    $profanity = "/(enter rude words here seperated by a |)/i";
    $spamwords = "/(enter spam words here seperated by a |)/i";
    $bots = "/(Indy|Blaiz|Java|libwww-perl|Python|OutfoxBot|User-Agent|PycURL|AlphaServer)/i";

    if (preg_match($bots, $_SERVER['HTTP_USER_AGENT'])) {
        exit("<p>Known spam bots are not allowed.</p>");
    }
    foreach ($_POST as $key => $value) {
        $value = trim($value);

        if (empty($value)) {
            exit("<p>Empty fields are not allowed. Please go back and fill in the form.</p>");
        } elseif (preg_match($exploits, $value)) {
            exit("<p>Exploits/malicious scripting attributes aren't allowed.</p>");
        } elseif (preg_match($profanity, $value) || preg_match($spamwords, $value)) {
            exit("<p>That kind of language is not allowed through our form.</p>");
        }

        $_POST[$key] = stripslashes(strip_tags($value));
    }

    if (!ereg("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,6})$",strtolower($_POST['email']))) {
        exit("<p>This is not a valid email address. Please press back and ammend the form.</p>");
    }

    $recipient = "youremail@yourdomain";
    $subject = "Contact From Your Company";

    $message = "You've received an enquiry from: \n";
    $message .= "Name: {$_POST['name']} \n";
    $message .= "E-mail: {$_POST['email']} \n";
    $message .= "Telephone: {$_POST['telephone']} \n";
    $message .= "Enquiry: {$_POST['enquiry']} \n";
    $message .= "Callback: {$_POST['callback']} \n";
    $message .= "Hearabout: {$_POST['hearabout']} \n";

    $headers = "From: Your Company <$recipient> \n";
    $headers .= "Reply-To: <{$_POST['email']}>";

    if (mail($recipient,$subject,$message,$headers)) {
        header ("Location: http://www.yourdomain.com/thankyou.php");
    } else {
        header ("Location: http://www.yourdomain.com/opps.php");
    }
}

$name = $_POST['name'];
$telephone = $_POST['telephone'];
$email = $_POST['email'];

$address = localhost;
$username = "db username";
$password = "db password";
$database = "db";

mysql_connect($address,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");

$query = "INSERT INTO contacts VALUES ('$id','$name','$telephone','$email')";
print($query);
mysql_query($query);

mysql_close();



?>

Basically create a form which when you submit it fires up this code and enters the varibles into the database. I used it for a company who wanted to mail shot out to clients at a later date. :)

Relevant HTML here:

Code:
<form id="enquiryform" action="form-process.php" method="post">
<p><label for="name">Name:</label><input type="text" class="required" id="name" name="name" maxlength="60" /><span class="warning">*</span></p>

<p><label for="country">Country:</label>
<select id="country" name="country">
<option value="United Kingdom" selected="selected">United Kingdom</option>
<option value="Europe">Europe</option>
</select></p>

<p><label for="postcode">Postcode:</label><input type="text" id="postcode" name="postcode" maxlength="20"  /></p>

<p><label for="telephone">Telephone:</label><input type="text" id="telephone" name="telephone" maxlength="30"  /></p>

<p><label for="email">Email:</label><input type="text" class="email required" id="email" name="email" maxlength="100" /><span class="warning">*</span></p>

<p><label for="enquiry">Your enquiry:</label><textarea class="required" rows="4" cols="40" id="enquiry" name="enquiry" ></textarea><span class="warning">*</span></p>

<p><label for="callback">Please call me back:</label>
<select id="callback" name="callback" >
<option value="Anytime">Anytime</option>
<option value="Morning">Morning</option>
<option value="Afternoon">Afternoon</option>
<option value="Evening">Evening</option>
<option value="No">No thanks</option>
</select></p>

<p><label for="hearabout">Where did you hear about us?</label>
<select id="hearabout" name="hearabout" tabindex="109">
<option value="Other">Other</option>
<option value="Already a customer">Already a customer</option>
<option value="Search engine">Search engine</option>
<option value="Referred by a friend">Referred by a friend</option>
<option value="Magazine/newspaper advert">Magazine/newspaper advert</option>
</select></p>
<p><input type="submit" class="button" name="submit" value="Submit Enquiry"  /></p>
</form>
 
Back
Top Bottom