You’ve been creating great web pages with HTML, and a sprinkling of CSS. But you’ve noticed that visitors to your site can’t do much other than passively look at the content on the pages. The communication’s one-way, and you’d like to change that. In fact, you’d really like to know what your audience is thinking. But you need to be able to allow users to enter information into a web form so that you can find out what’s on their minds. And you need to be able to process the information and have it delivered to you. It sounds as if you’re going to need more than HTML to take your site to the next level.
HTML’s great for creating web pages, that much we already know. But what about when you need web pages that actually do something? Suppose you need to search a database or send an email... what then? HTML falls short because it’s a pretty lifeless language, designed for displaying information that never changes.
With pure HTML web pages, the server simply serves up static HTML that can only display content.
The web server’s a big part of the problem with lifeless HTML since it serves as nothing more than a boring delivery mechanism. A browser requests a page, the server responds with HTML, end of story. To turn web sites into interactive web applications, the web server has to take on a new, more dynamic role... a role made possible by PHP.
PHP allows you to manipulate web page content on the server just before a page is delivered to the client browser. It works like this: A PHP script runs on the server and can alter or generate HTML code at will. An HTML web page is still delivered to the browser, which doesn’t know or care that PHP is involved in tweaking the HTML on the server.
With PHP in the mix, the web server is able to dynamically generate HTML web pages on the fly.
Meet Owen. Owen’s lost his dog, Fang. But finding his dog isn’t just a matter of searching the neighborhood. You see, Fang was abducted by aliens, which expands Owen’s search to the entire galaxy. Owen knows some HTML and CSS, and he thinks a custom web site may help solve his problem by allowing other people to share their own alien abduction experiences.
But to get information from others, Owen’s going to need a web form that’s capable of receiving user input, lots of it, and notifying him about it. Not a problem—HTML has plenty of tags for whipping together web forms.
Owen’s new web site, AliensAbductedMe.com, aims to connect Owen with alien abductees who might be able to shed some light on Fang’s disappearance. Owen knows he needs an HTML form to solicit abduction stories from visitors and that it must find out if they’ve run into Fang during their interstellar journeys. But he needs your help getting it up and running. Here’s what he has in mind for the form.
What do you think of Owen’s HTML form?
Can you think of any problems Owen might face when he tries to gather alien abduction data using this form? Go ahead, jot down your thoughts.
__________________________________________
__________________________________________
__________________________________________
Owen’s Report an Abduction form is built entirely out of HTML tags and attributes. There are text fields for most of the questions, radio buttons to find out if his visitor saw Fang, and a text area for additional comments. And the form is set up to deliver form data to Owen’s email address.
Owen’s Report an Abduction form is up and running, but he doesn’t get much information from users. Is Fang’s abduction really such an isolated incident... or is something wrong with his form? Let’s see what the users have to say about it.
What’s going on here? Do you have any ideas about how to fix the form?
Yes. The HTML form code is fine, but mailto
isn’t a good way to deliver form data.
Owen’s form is perfectly fine until the user clicks the Report Abduction button. At that point you rely on mailto
to package up the form data in an email. But this email doesn’t get sent automatically—it’s created in the default email program on the user’s computer instead. And the real kicker... the user has to send the email themselves in order for the data to get sent to you! So you have no control over the email delivery, meaning that it may or may not successfully make the trip from your web form through their browser to their email client and back to you as an email message. Not good.
You need a way to take control of the delivery of the web form. More specifically, you need PHP to package the form data into an email message, and then make sure it gets sent. This involves shifting your attention from the client (HTML, mailto
, etc.) to the server (PHP).
Owen’s form is written in pure HTML with a mailto
form action that attempts to send the form data via email. Although the report.html
web page comes from a web server, it’s filled out and processed entirely on the user’s web browser.
The server’s role here is limited to just delivering the web page to the browser. When the user submits the form, the browser (client!) is left to its own devices to work out how to get the form data sent via email. The client isn’t equipped to deliver form data—that’s a job for the server.
PHP lets you take control of the data a user types into the form by emailing it to you transparently. The user types his abduction story into the form, hits the Report Abduction button, and he’s done! The PHP code creates the email message, sends it to you, and then generates a web page confirmation for the user.
Check the boxes for where you think a PHP script belongs:
PHP code runs on the server and is stored in PHP scripts that usually have a .php
file extension. PHP scripts often look a lot like normal HTML web pages because they can contain both HTML code and CSS code. In fact, when the server runs a PHP script the end result is always pure HTML and CSS. So every PHP script ultimately gets turned into HTML and CSS once it’s finished running on the server.
Let’s take a closer look at how a PHP script changes the flow of Owen’s web form.
PHP is a server-side programming language - it runs on a web server.
A form element’s action
attribute is what connects a form to a PHP script, causing the script to run when the form is submitted.
Forms are created using the HTML <form>
tag, and every <form>
tag has an action
attribute. Whatever filename you set the action
attribute to is used by the web server to process the form when it is submitted. So if Owen’s PHP script is named report.php
, then the <form>
tag that connects it to the form looks like this:
When the user clicks the Report Abduction button in the form, the form action causes the report.php
script to be run on the server to process the form data.
So Owen needs a PHP script that can get the alien abduction form information to him more reliably than the mailto
technique. Let’s create it. Don’t worry about understanding everything yet—we’ll get to that:
Unless you happen to have a web server running on your local computer, the report.php
script can’t run when you submit the Report an Abduction form. Remember, PHP is a programming language, and it needs an environment to run in. This environment is a web server with PHP support. PHP scripts and web pages that rely on the scripts must be placed on a real web server, as opposed to just opening a script directly from a local file system.
Note
If you do have a web server installed locally and it has PHP support, then you can test out PHP scripts directly on your local computer.
Web browsers know nothing about PHP and, therefore, have no ability to run PHP scripts.
Web servers with PHP support are equipped to run PHP scripts and turn them into HTML web pages that browsers can understand.
PHP scripts must be run on a web server or they won’t work.
It’s perfectly fine to create and edit PHP scripts on your local computer. But you need to put the files on a web server to run them. PHP files are often placed alongside HTML files on a web server. There’s nothing magical about putting PHP scripts on a web server—just upload them to a place where your web pages can access them. Uploading files to a web server requires the help of a utility, such as an FTP (File Transfer Protocol) utility.
Uploading your PHP scripts to a web server isn’t enough—that web server must also have PHP installed on it. Some web servers include PHP by default, some don’t.
Relax
If you don’t have PHP installed on your web server, check out Appendix B.
You’ll find instructions here for getting PHP up and running on your web server.
That’s right. The report.php
script’s still missing code to email the alien abduction data to Owen.
But that’s not a problem because PHP offers a function, a pre-built chunk of reusable code, that you can use to send email messages. You just need to figure out what the email message needs to say and then use PHP to create and send it.
It’s true. Doing more with PHP requires knowing more about PHP.
So in order to add email functionality to Owen’s report.php
script, you’re going to have to dig a little deeper into PHP and get a solid handle on how the script works up to this point.
A big part of understanding how a PHP script works is getting a handle on what happens to the script when it runs on the server. Most PHP scripts contain both PHP code and HTML code, and the PHP’s run and turned into HTML before the server passes the whole thing off as HTML to the client web browser. In Owen’s report.php
script, PHP code generates most of the HTML content in the body of the confirmation page. The HTML code surrounding it is delivered unchanged.
The report.php
script is triggered by the Report an Abduction form, and its job (at the moment) is to take the form data and generate a confirmation web page. Let’s see how.
The first chunk of code is pure HTML. It just sets up the page we’re building, including a few HTML tags required of all pages.
Here’s where things start to get interesting. We’re ready to break out of HTML code and into PHP code. The <?php
tag opens a section of PHP code—everything following this tag is pure PHP.
This code grabs the form data and stores it away in individual variables so that we can easily access it later. PHP variables allow you to store values, be they numbers, text, or other kinds of data.
Now we’re talking! Here the variables we just created are put to work by inserting them into dynamically generated HTML code. The echo
command outputs HTML code that gets returned directly to the web browser.
The ?>
tag matches up with <?php
and closes up a section of PHP code. From here on, we’re back to normal HTML code.
Now wrap up the page by closing out the HTML tags we opened earlier.
Owen’s report.php
script reveals a few fundamental rules of the PHP language that apply to all PHP scripts. Let’s take a look at them.
Given the variables used in the report.php
script, do you see any other PHP rules pertaining to variables? Write ‘em down!
__________________________________________
__________________________________________
__________________________________________
In addition to starting with a $
, PHP variable names are also case-sensitive. But that’s not all—there are other important rules governing how you name variables. Some of these rules are syntax rules, meaning your code will break if you ignore them, while other rules are just good ideas passed down from wise old PHP coders.
Let’s start with the official rules that will absolutely cause problems if you ignore them when naming variables. Follow these rules to create legal variable names.
A variable is a container that you can store data in, and every variable has a unique name.
These rules will stop your code working if you don’t follow them, but there are a couple more rules that are good to follow as more of a coding convention. These rules help make PHP code a little more consistent and easier to read.
PHP variable names must begin with a dollar $ sign, and cannot contain spaces.
These last two rules won’t break your code if you ignore them, and you’ll certainly run across PHP code that doesn’t adhere to them yet works just fine. This is because they are just a stylistic convention—but they will serve you well as you begin creating and naming variables of your own.
PHP variables are storage containers that store information kinda like how a cup stores a beverage. Since the $alien_description
variable is empty, we know that the form data is never making its way into it. So the $alien_description
variable remains empty despite our attempt to assign data to it.
One way to fix the script would be to just assign the exact string we’re expecting to the $alien_description
variable, like this:
This code works in that it most definitely stores the text 'little green men'
in the $alien_description
variable. But we solved one problem by creating another one—this code causes the alien description to always be the same regardless of what the user enters into the form.
Brain Power
Somehow the assignment of alien description form data to the $alien_description
variable is coming up empty.
$alien_description = $_POST['description'];
What do you think this code is doing wrong?
The problem does have to do with $_POST
, which is a mechanism used to pass along form data to a script.
The dollar sign at the beginning of $_POST
is a clue... $_POST
is a storage container! More specifically, $_POST
is a collection of storage locations used to hold data from a web form. In Owen’s case, it holds all the data that gets sent to our report.php
script when someone fills out the form and clicks the Report Abduction button. So in order to access the form data and do anything with it, we have to go through $_POST
. Remember this code?
So the data in each field of the Report an Abduction form is accessed using $_POST
. But what exactly is $_POST
... a variable?
$_POST
is a special variable that is known as a superglobal because it is built into PHP and is available throughout an entire script. $_POST
already exists when your script runs—you don’t create it like you do other PHP variables.
The $_POST
superglobal is directly tied to the form submission method used by the HTML form. If the method’s set to post
, then all of the form data gets packaged into the $_POST
superglobal, where each piece of data can be plucked out and used as needed.
$_POST
is a special kind of PHP storage container known as an array, which stores a collection of variables under a single name. When someone submits Owen’s form, the data they’ve typed into the form fields is stored in the $_POST
array, whose job is to pass the data along to the script.
Each element in the $_POST
array corresponds to a piece of data entered into a form field. To access the data for a specific form field, you use the name of the field with $_POST
. So the duration of an abduction is stored in $_POST['howlong']
. The HTML code for Owen’s form reveals how form names relate to data stored in $_POST
.
The $_POST array is filled with the values the user entered into the form.
The PHP script still needs to email the form data to Owen.
As it stands, the report.php
script is grabbing the data from the Report an Abduction form and generating an HTML confirmation page for the user. But it’s not yet solving the original problem of emailing a message to Owen when the form is submitted. He just wants to receive a simple text email message that looks something like this:
Alf Nader was abducted last November and was gone for 11 hours. |
Number of aliens: dozens |
Alien description: little green men |
What they did: asked me about UFO regulations |
Fang spotted: no |
Other comments: Please vote for me. |
This email message can be generated from PHP code by putting together a string that combines static text such as "Other comments:"
with form field data stored in variables.
Write down how you’d put together an email message string from static text and PHP variables.
__________________________________________
__________________________________________
You’ve already seen how a period can be used in PHP code to concatenate multiple strings of text together into a single string. Now you need to use concatenation again to build an email message string with variables sprinkled in among static text.
One problem with building such a large string is that it requires a huge line of PHP code that’s difficult to read and understand. You can break the PHP code across multiple lines to make it easier to follow. Just make sure to separate the code in spots where the spacing doesn’t matter, like between two concatenated strings, not in the middle of a string. Then put a semicolon at the end of the last line of the code to finish the PHP statement.
A long line of PHP code can be spanned across multiple lines as long as you’re careful about how you break up the code.
Yes. Just because the PHP code is organized nicely doesn’t mean its output will automatically look good.
Organizing PHP code so that you can better understand it is completely different than formatting the output of PHP code that users will see. You’ll normally use HTML tags to format the output of PHP code since in most cases PHP is used to dynamically generate a web page. But not in this case.
Here we’re generating an email message, which is plain text, not HTML. We need to deal with the fact that the message currently looks like this:
Alf Nader was abducted last November and was gone for 11 hours. Number of aliens: dozensAlien description: little green menWhat they did: asked me about UFO regulationsFang spotted: noOther comments: Please vote for me. |
Since Owen’s sending email messages as plain text with no HTML formatting, he can’t just stick in <br />
tags to add line breaks where the content’s running together. But he can use newline characters, which are escaped as \n
. So wherever \n
appears in the email text, a newline will be inserted, causing any content after it to start on the next line. Here’s the new email message code with newlines added:
Escape characters in PHP start with a backslash (\).
The problem with Owen’s code is that PHP handles strings differently depending on whether they’re enclosed by single or double quotes. More specifically, newline characters (\n
) can only be escaped in double-quoted strings. So the Abduction Report email message must be constructed using double-quoted strings in order for the newlines to work.
But there’s more to the single vs. double quote story than that. Single-quoted strings are considered raw text, whereas PHP processes double-quoted strings looking for variables. When a variable is encountered within a double-quoted string, PHP inserts its value into the string as if the strings had been concatenated. So not only is a double-quoted string necessary to make the newlines work in the email message, but it also allows us to simplify the code by sticking the variables directly in the string.
With the body of the email message generated as a string, you can move on to assembling the rest of Owen’s email. An email message is more than just a message body—there are several different parts. Although some are optional, the following pieces of information are used in pretty much all emails:
The message body. Already done!
The message subject.
The sender’s email address (who the message is FROM).
The recipient’s email address (who the message is TO).
This is the kind of email message Owen hopes to receive upon someone submitting an alien abduction report.
This sample email message reveals that most of the content is in the body of a message, which you’ve already finished. All that’s left is coming up with a message subject, “from” and “to” email addresses... and of course, somehow using PHP to actually send the message!
We already have the message body stored in $msg
, but we’re still missing the message subject and “from” and “to” email addresses. The subject and the “to” email address can just be set as static text in new variables, while the “from” email address is already stored away in the $email
variable thanks to the form-handling code we wrote earlier in the chapter.
So you’re ready to write the PHP code to actually send the email message to Owen. This requires PHP’s built-in mail()
function, which sends a message based on information you provide it.
The PHP mail() function sends an email message from within a script.
These three pieces of information are required by the mail()
function, so you always need to provide them. The “from” email address isn’t required but it’s still a good idea to include it. To specify the “from” field when calling the mail()
function, an additional function argument’s required, along with some string concatenation.
Just add the code that calls mail()
to your script.
The line of code that calls the mail()
function is all you need to send the email message. Make sure this code appears in the script after the code that creates the email variables, and you’re good to go. Here’s the complete code for Owen’s report.php
script, including the call to the mail()
function.
Watch it!
You may need to configure PHP on your web server so it knows how to send email.
If the mail()
function doesn’t work for you, the problem may be that email support isn’t properly configured for your PHP installation. Check out www.php.net/mail
for details on how to configure email features on your web server.
Owen is thrilled that he’s reliably receiving alien abduction information from a web form directly to his email Inbox. Now he doesn’t have to worry if he hears that someone saw his dog because he’ll have email addresses from everyone who contacts him. And even better, he’ll be able to look through the responses at his leisure.
The good news is that Owen’s getting emails now. The bad news is that he’s getting lots and lots of emails. So many that he’s having difficulty keeping track of them. His Inbox is packed, and he’s already accidentally deleted some... Owen needs a better way to store the alien abduction data.
In Chapter 1, you learned how to harness PHP to bring life to Owen’s web form. Look at everything you’ve learned already...
Get Head First PHP & MySQL now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.