PHP Part 3 — Functions & Includes
We’ll begin this article with some plain old HTML.
We will make a contact form, and then attempt to validate all the data.
Once we have all the data validated, we will email the details to our imaginary site administrators to check and reply to any comments.
The operators we covered in part 2 of the series will be used over and over here, so if you’re not confident in using these, a quick flick through them again would be advisable.
Right, let’s get to it...
Building the HTML, with Includes
First of all, let’s build the plain HTML.
This will give us the chance to see what data we want, and we can start to formulate plans on how to deal with it.
We will call the page contactform.php, put it in our base directory (probably located at c:\phpdev\www if you are developing on your home Windows PC).
We use <?=$_SERVER['PHP_SELF']?> to get the name of the page, so that it submits back to itself.
Note that this will return the name of the page that the browser is looking at, not necessarily the page that the code is on.
This will become clear in a second.
So here it is:
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="submitted" value="true" />
Your name:
<br />
<input type="text" name="name" value="" />
<br />
Your Email Address:
<br />
<input type="text" name="email" value="" />
<br />
Your Comments
<br />
<textarea name="comments"></textarea>
<br />
<input type="submit" value="Send the comments!" />
</form>
We will also build a page called contact.php, where all the magic happens.
From this page we will include contactform.php, like so:
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Me</h1>
<p>Use the form to get in touch with our imaginary company...</p>
<?php
include 'contactform.php';
?>
</body>
</html>
The include statement will take everything in the file specified, and dump it into the main file at that point.
So if you point your browser at http://localhost/contact.php, you should now see the contact page, with the HTML for the form included.
Any PHP in the include file will also be parsed, so <?=$_SERVER['PHP_SELF']?> has been parsed as contact.php.
Showing the data
Now, if you submit the form, nothing seems to happen.
Everything is working fine, but the data you have sent is just floating around, not being used.
Let’s use a little PHP to show the data you sent through.
<?php
$submitted = $_POST["submitted"];
if ($submitted == true) {
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
}
?>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Me</h1>
<p>Use the form to get in touch with our imaginary company...</p>
<?php
include 'contactform.php';
if ($submitted == true) {
echo 'You entered the following details:<br />';
echo 'Name: ' . $name . '<br />';
echo 'Email Address: ' . $email . '<br />';
echo 'Comments: ' . $comments . '<br />';
}
?>
</body>
</html>
Very simply, all we have done here is to find out if the form has been posted (by testing if our hidden field called "submitted" is set), and to display the data if appropriate.
We have used the $_POST construct to access form data sent to the page.
As of PHP4, this is the standard way to do it, and I would advise against trying to do it any other way.
If you need to get querystring data, for instance if your form used method="get", you would use $_GET instead.
Later on we will modify this page, so that instead of showing us the posted data, it will email it to us, but for now it is useful to see the data, so we can debug it and spot any errors.
Catching Errors
We still have our limitations here, and chief among them is the fact that we don’t tell the user off if they do not fill in some of the fields we want them to.
Let’s have another hack about with the code, and add some error checking to the mix...
Within this block of code, there is also the first built in function of PHP that you have come across.
It goes by the name of strlen (which is short for "string length"), and you feed it one item, a string, and in return it will tell you the length of said string.
We use it here as if a supplied email address is less than 6 characters long, it cannot possibly be valid.
The shortest possible address would be something like i@a.it, 6 characters exactly.
<?php
$submitted = $_POST["submitted"];
$error = '';
if ($submitted == true) {
$name = $_POST["name"];
if ($name == '') {
$error .= 'You did not specify your name!<br />';
}
$email = $_POST["email"];
if (strlen($email) < 6) {
$error .= 'You did not specify a valid email address!<br />';
}
$comments = $_POST["comments"];
if ($comments == '') {
$error .= 'You did not specify a comment for us!<br />';
}
}
?>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Me</h1>
<p>Use the form to get in touch with our imaginary company...</p>
<?php
if ($error) {
echo '<p><b>The following errors occured: <br />';
echo $error;
echo '</b></p>';
}
include 'contactform.php';
if ($submitted == true) {
echo 'You entered the following details:<br />';
echo 'Name: ' . $name . '<br />';
echo 'Email Address: ' . $email . '<br />';
echo 'Comments: ' . $comments . '<br />';
}
?>
</body>
</html>
As I’m sure you have experienced it before, you will know there is nothing more annoying than making a mistake on a form, and then having to fill in all the fields again.
Luckily, it’s easy to put the values back into the fields, so we’ll do that now, using <?=.
This is a shorthand for <?php echo, and can be used when you have just a variable to echo to the user.
We have already been using it to put in the name of the page if you look carefully.
If you feel more comfortable, you may continue to use <?php echo $comments; ?>, as it works in the same way.
So open up contactform.php, and change it to the following:
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="submitted" value="true" />
Your name:
<br />
<input type="text" name="name" value="<?=$name?>" />
<br />
Your Email Address:
<br />
<input type="text" name="email" value="<?=$email?>" />
<br />
Your Comments
<br />
<textarea name="comments"><?=$comments?></textarea>
<br />
<input type="submit" value="Send the comments!" />
</form>
As the variables were defined before we included contactform.php, they were all available to it, and so the PHP was parsed correctly.
More Error Checking
We are still far from having a bulletproof form here, as a user could just enter 123456 as their email address and that would be ok.
So let’s add some checks, one for a dot in the right place, and one for an @ symbol, using some more of the built in PHP functions.
<?php
$submitted = $_POST["submitted"];
$error = '';
if ($submitted == true) {
$name = $_POST["name"];
if ($name == '') {
$error .= 'You did not specify your name!<br />';
}
$email = $_POST["email"];
if (strlen($email) < 6) {
$error .= 'The email address is not long enough!<br />';
} else {
$atarray = explode('@',$email);
if (!$atarray[0] || !$atarray[1] || $atarray[2]) {
$error .= 'There is the wrong amount of @ symbols in the email address, ';
$error .= 'or they are in the wrong place!<br />';
} else {
$dotarray = explode('.',$atarray[1]);
$lastbit = end($dotarray);
if (!$dotarray[0] || !$dotarray[1] || strlen($lastbit) < 2 || strlen($lastbit) > 4) {
$error .= 'There are no dots in the email address, ';
$error .= 'or they are in the wrong place!<br />';
}
}
}
$comments = $_POST["comments"];
if ($comments == '') {
$error .= 'You did not specify a comment for us!<br />';
}
}
?>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Me</h1>
<p>Use the form to get in touch with our imaginary company...</p>
<?php
if ($error) {
echo '<p><b>The following errors occured: <br />';
echo $error;
echo '</b></p>';
}
include 'contactform.php';
if ($submitted == true) {
echo 'You entered the following details:<br />';
echo 'Name: ' . $name . '<br />';
echo 'Email Address: ' . $email . '<br />';
echo 'Comments: ' . $comments . '<br />';
}
?>
</body>
</html>
Phew, that’s a meaty bit of code for you. Don’t worry if you dont’t get it, I shall explain it bit by bit.
First up, we check that the email address is at least 6 characters long as before.
If not, we return an error.
However, if it is long enough, some more investigation is called for...
We use explode to create an array.
Arrays are variables that contain lots of values, and you get to each one through $mayvariable[0] for the first value, $mayvariable[1] for the second and so on...
We wil cover them in much more depth in the next lesson, but that’s enough to know for now.
Explode takes a string, and breaks it up into an array of smaller parts, making the breaks wherever it finds a certain string (in this case the @ symbol).
We then make sure that there are only 2 bits broken off (a bit before an @ and a bit after), by checking $atarray[0] exists (part 1), as does $atarray[1] (part 2).
If $atarray[2] existed, we would know we must have 2 @ symbols in the string, which isn’t allowed.
We have put an exclamation mark before the first 2 to indicate "not", so if we were to read the line if (!$atarray[0] || !$atarray[1] || $atarray[2]) {, it would go something like:
"if (not a bit before an @ OR not a bit after an @ OR a bit after a second @) then...".
Assuming that part is ok, we move on to check that there is at last one dot after the @ symbol.
We get the last part of the previous array from $atarray[1], and break that up again with explode, but this time about the dots.
We then find out what the last bit to be broken off was, using PHPs built in function end.
Finally, we check that there is a bit before and after a dot, and that the last bit is between 2 and 4 characters long — for example .it, .com or .info adresses.
If at any point one of the above conditions is not met, it will generate an error and put it into our error string for printing out later.
We now have a pretty good (although not infallible) email address validation script, so we might decide we want to use this elsewhere on our site, for instance when users sign up.
We could just copy and paste it into every page that needs it, but it would make far more sense to write it once and then use it as and when we need it.
If only there was a way...
Creating Your Own Functions
Luckily, I’m not the first person to have thought of that, so PHP has a way to make your own functions to add to PHPs existing ones.
Let’s create one to validate email addresses. We’ll call it validemail, and then use it in our script.
<?php
function validemail($someaddress) {
if (strlen($someaddress) < 6) {
return false;
} else {
$atarray = explode('@',$someaddress);
if (!$atarray[0] || !$atarray[1] || $atarray[2]) {
return false;
} else {
$dotarray = explode('.',$atarray[1]);
$lastbit = end($dotarray);
if (!$dotarray[0] || !$dotarray[1] || strlen($lastbit) < 2 || strlen($lastbit) > 4) {
return false;
} else {
return true;
}
}
}
}
$submitted = $_POST["submitted"];
$error = '';
if ($submitted == true) {
$name = $_POST["name"];
if ($name == '') {
$error .= 'You did not specify your name!<br />';
}
$email = $_POST["email"];
if (!validemail($email)) {
$error .= 'You did not specify a valid email address.<br />';
}
$comments = $_POST["comments"];
if ($comments == '') {
$error .= 'You did not specify a comment for us!<br />';
}
}
?>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Me</h1>
<p>Use the form to get in touch with our imaginary company...</p>
<?php
if ($error) {
echo '<p><b>The following errors occured: <br />';
echo $error;
echo '</b></p>';
}
include 'contactform.php';
if ($submitted == true) {
echo 'You entered the following details:<br />';
echo 'Name: ' . $name . '<br />';
echo 'Email Address: ' . $email . '<br />';
echo 'Comments: ' . $comments . '<br />';
}
?>
</body>
</html>
So there you have it, a function defined by you.
It takes one parameter, a string, and checks to see if it makes a valid email address.
If it does, the function returns the value true, otherwise it returns false.
You could make it return whatever you liked, using the keyword return, but true or false is good enough for this.
All you have to do now is put this function in an include file (I like to keep all my functions in one file, and include the file at the top of any pages I need some of the functions for), and then call validemail() as you would a built-in PHP function.
Clever stuff.
Sending Emails
Sending emails in PHP really couldn’t be easier.
We will use the PHP function mail(), which takes four parameters, one of which is optional.
First up we need to specify who the email should be sent to, followed by the email’s subject, then the message itself, and finally we may specify “additional headers”.
Additional headers are used to change things like the reply-to address and the from address, as well as adding CC details.
We will use these to specify a reply address so that our site administrators can directly reply to the email.
So here’s the coded in all it’s glory (we have assumed that the validemail() function we wrote earlier has been moved into an include file called validemailinclude.php):
<?php
include 'validemailinclude.php';
$submitted = $_POST["submitted"];
$error = '';
if ($submitted == true) {
$name = $_POST["name"];
if ($name == '') {
$error .= 'You did not specify your name!<br />';
}
$email = $_POST["email"];
if (!validemail($email)) {
$error .= 'You did not specify a valid email address.<br />';
}
$comments = $_POST["comments"];
if ($comments == '') {
$error .= 'You did not specify a comment for us!<br />';
}
}
?>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Me</h1>
<p>Use the form to get in touch with our imaginary company...</p>
<?php
if ($error) {
echo '<p><b>The following errors occured: <br />';
echo $error;
echo '</b></p>';
}
include 'contactform.php';
if ($submitted == true && !$error) {
$to = 'admin@mydomain.com';
$subject = 'Email from ' . $name . ', through our website!';
$additional = "From: " . $email;
if (mail($to, $subject, $comments, $additional)) {
//email is on its way!
echo 'Thank you for contacting us ' . $name . ', we will reply to your email shortly';
} else {
//Your server cannot send emails, if you are developing locally this will happen.
echo 'An error occured, this server is not set up to send email. Sorry...';
}
?>
</body>
</html>
If all things went well, admin@mydomain.com should receive an email that claims to be from the user who used the form.
The administrators can now freely reply to this message and sort out the users query.
If you have problems getting this function to work, and it times out and says “An error occured, this server is not set up to send email. Sorry...”, this is because your server is not able to send emails.
If you are developing in http://localhost this will happen, so you must upload the file to a live server to check it.
Coming up Next...
Next lesson, we cover MySQL in some depth, and get started on building a database driven site, with plenty of dynamic content.
See y’all next time...