After learning php I've written my first script, a simple mailform. Could you check whether it's any good? I'm especially curious about the following:
- are the name and email check regex constructed right?
- http_referrer is unreliable I've read. Now I'm using sessions to check whether my script is called from my own site. Did I do this right?
For the rest I've place comments which say what each part is supposed to do? Any errors? Of tips to make it work better?
First a small part of the mail.htm form:
<?php
session_start();
$_SESSION["password"] = "myform";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Mailform</title>
</head>
<body>
Next the mail processing php:
<?php
session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Mailformulier</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
/* Called from my own site? */
$wachtwoord = $_SESSION["password"];
if ($wachtwoord != "myform") {
echo "Don't touch my script!";
exit;
}
/* Email settings */
$to = "mijn@emailadres.nl";
$subject = "Een mailtje via de website";
$redirectgoed = "mailsend.htm";
$redirectfout = "mailfout.htm";
/* Check if a real name is used */
function testnaam ($str) {
return (ereg ('^[A-Za-z][A-Za-z -]*$', $str));
}
/* Check if a real email address is used */
function testmail ($str) {
return (ereg ('^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$', $str));
}
/* Form filled in wrong or not at all? */
if ($_POST["verstuurknop"] !="Versturen" || !testnaam($_POST["afzender"]) || !testmail($_POST["mailadres"]) || !$_POST["mailbericht"]) {
header("location:".$redirectfout);
} else {
/* Mail is sent */
$message = "Naam:\n".$_POST["afzender"]."\n\nEmailadres:\n".$_POST["mailadres"]."\n\nBericht:\n".htmlspecialchars($_POST["mailbericht"]);
$headers = "From: ".$_POST["mailadres"]);
mail($to, $subject, $message, $headers);
header("location:".$redirectgoed);
}
?>
</body>
</html>