You are previewing Head First PHP & MySQL.

Head First PHP & MySQL

Cover of Head First PHP & MySQL by Michael Morrison... Published by O'Reilly Media, Inc.
  1. Head First PHP & MySQL
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Advance Praise for Head First PHP & MySQL
  5. Praise for Head First HTML with CSS & XHTML
  6. Praise for Head First JavaScript
  7. Author(s) of Head First PHP & MySQL
  8. How to Use This Book: Intro
    1. Who is this book for?
    2. Who should probably back away from this book?
    3. We know what you’re thinking
    4. We know what your brain is thinking
    5. Metacognition: thinking about thinking
    6. Here’s what WE did:
    7. Here’s what YOU can do to bend your brain into submission
    8. Read Me
    9. The technical review team
    10. Acknowledgments
    11. Safari Books Online
  9. 1. Add Life to your Static Pages: It’s Alive
    1. HTML is static and boring
    2. PHP brings web pages to life
    3. Dogs in space
    4. A form helps Owen get the whole story
    5. Forms are made of HTML
    6. The HTML form has problems
    7. HTML acts on the CLIENT
    8. PHP acts on the SERVER
    9. PHP scripts run on the server
    10. Use PHP to access the form data
    11. PHP scripts must live on a server!
    12. Get your PHP scripts to the server
    13. The server turns PHP into HTML
    14. Deconstructing Owen’s PHP script
    15. A few PHP rules to live code by
    16. Finding the perfect variable name
    17. Variables are for storing script data
    18. $–POST is a special variable that holds form data
    19. $–POST transports form data to your script
    20. Creating the email message body with PHP
    21. Even plain text can be formatted... a little
    22. Newlines need double-quoted strings
    23. Assemble an email message for Owen
    24. Variables store the email pieces and parts
    25. Sending an email message with PHP
    26. Owen starts getting emails
    27. Owen starts losing emails
    28. Your PHP & MySQL Toolbox
  10. 2. Connecting to MySQL: How it fits together
    1. Owen’s PHP form works well. Too well...
    2. MySQL excels at storing data
    3. Owen needs a MySQL database
    4. Create a MySQL database and table
    5. The INSERT statement in action
    6. Use SELECT to get table data
    7. Let PHP handle the tedious SQL stuff
    8. PHP lets data drive Owen’s web form
    9. Connect to your database from PHP
    10. Insert data with a PHP script
    11. Use PHP functions to talk to the database
    12. Get connected with mysqli_connect()
    13. Build the INSERT query in PHP
    14. Query the MySQL database with PHP
    15. Close your connection with mysqli–close()
    16. $–POST provides the form data
    17. Owen needs help sifting through his data
    18. Owen’s on his way to finding Fang
  11. 3. Create and Populate a Database: Creating your own data
    1. The Elvis store is open for business
    2. Elmer needs an application
    3. Visualize Elmer’s application design
    4. It all starts with a table
    5. Make contact with the MySQL server
    6. Create a database for Elmer’s emails
    7. Create a table inside the database
    8. We need to define our data
    9. Take a meeting with some MySQL data types
    10. Create your table with a query
    11. Getting the cart table in front of the horse database
    12. USE the database before you use it
    13. DESCRIBE reveals the structure of tables
    14. Elmer’s ready to store data
    15. Create the Add Email script
    16. The other side of Elmer’s application
    17. The nuts and bolts of the Send Email script
    18. First things first, grab the data
    19. mysqli_fetch_array() fetches query results
    20. Looping for a WHILE
    21. Looping through data with while
    22. You’ve got mail...from Elmer!
    23. Sometimes people want out
    24. Removing data with DELETE
    25. Use WHERE to DELETE specific data
    26. Minimize the risk of accidental deletions
    27. MakeMeElvis.com is a web application
    28. Your PHP & MySQL Toolbox
  12. 4. Realistic and Practical Applications: Your Application on the Web
    1. Elmer has some irritated customers
    2. Protecting Elmer from... Elmer
    3. Demand good form data
    4. The logic behind Send Email validation
    5. Your code can make decisions with IF
    6. Testing for truth
    7. IF checks for more than just equality
    8. The logic behind Send Email validation
    9. PHP functions for verifying variables
    10. Test multiple conditions with AND and OR
    11. Form users need feedback
    12. Ease in and out of PHP as needed
    13. Use a flag to avoid duplicate code
    14. Code the HTML form only once
    15. A form that references itself
    16. Point the form action at the script
    17. Check to see if the form has been submitted
    18. Some users are still disgruntled
    19. Table rows should be uniquely identifiable
      1. What Elmer’s table contains now:
      2. What Elmer’s table should contain:
    20. Primary keys enforce uniqueness
    21. The five rules of primary keys:
    22. From checkboxes to customer IDs
    23. Loop through an array with foreach
    24. Your PHP & MySQL Toolbox
  13. 5. Working with Data Stored in Files: When a database just isn’t enough
    1. Virtual guitarists like to compete
      1. Text can’t be trusted
    2. The proof is in the rockin’ picture
    3. The application needs to store images
    4. Planning for image file uploads in Guitar Wars
    5. The high score database must be ALTERed
    6. How do we get an image from the user?
    7. Insert the image filename into the database
    8. Find out the name of the uploaded file
    9. Where did the uploaded file go?
    10. Create a home for uploaded image files
    11. Shared data has to be shared
    12. Shared script data is required
    13. Think of require_once as “insert”
    14. Timing Order is everything with high scores
    15. Honoring the top Guitar Warrior
    16. Format the top score with HTML and CSS
    17. Only small images allowed
    18. File validation makes the app more robust
    19. Plan for an Admin page
      1. These pages are for users:
      2. This page is only for the administrator:
    20. Generate score removal links on the Admin page
    21. Scripts can communicate with each other
    22. Of GETs and POSTs
    23. GET, POST, and high score removal
    24. Isolate the high score for deletion
    25. Control how much you delete with LIMIT
    26. Your PHP & MySQL Toolbox
  14. 6. Securing your Application: Assume they’re all out to get you
    1. The day the music died
    2. Where did the high scores go?
    3. Securing the teeming hordes
    4. Protecting the Guitar Wars Admin page
    5. HTTP authentication requires headers
    6. Take control of headers with PHP
    7. Authenticating with headers
      1. OK, so maybe Guitar Wars is NOT secure
    8. Create an Authorize script
    9. Guitar Wars Episode II : Attack of the High Score Clones
    10. Subtraction by addition
    11. Security requires humans
    12. Plan for moderation in Guitar Wars
    13. Make room for approvals with ALTER
    14. Unapproved scores aren’t worthy
    15. The million-point hack
    16. Everything in moderation... ?
    17. How exactly did she do it?
    18. Tricking MySQL with comments
    19. The Add Score form was SQL injected
    20. Protect your data from SQL injections
    21. A safer INSERT (with parameters)
    22. Form validation can never be too smart
    23. Cease fire!
    24. Your PHP & MySQL Toolbox
  15. 7. building personalized web apps: Remember me?
    1. They say opposites attract
    2. Mismatch is all about personal data
    3. Mismatch needs user log-ins
      1. Username
      2. Password
    4. Come up with a user log-in gameplan
    5. Prepping the database for log-ins
    6. Constructing a log-in user interface
    7. Encrypt passwords with SHA()
    8. Decrypting Comparing passwords
      1. Making room for the encrypted password
    9. Authorizing users with HTTP
    10. Logging In Users with HTTP Authentication
    11. A form for signing up new users
    12. Give users a chance to sign up
    13. Sometimes you just need a cookie
    14. What’s in a cookie?
    15. Bake Use cookies with PHP
    16. Rethinking the flow of log-ins
    17. A cookie-powered log-in
    18. Navigating the Mismatch application
    19. Logging out means deleting cookies
    20. Sessions aren’t dependent on the client
    21. The life and times of sessions
    22. Keeping up with session data
    23. Renovate Mismatch with sessions
    24. Log out with sessions
    25. Complete the session transformation
    26. Users aren’t feeling welcome
    27. Sessions are short-lived...
    28. ... but cookies can last forever!
    29. Sessions + Cookies = Superior log-in persistence
  16. 8. Eliminate Duplicate Code: Sharing is caring
    1. Mismatch is in pieces
    2. Rebuilding Mismatch from a template
    3. Rebuild Mismatch with templates
    4. Mismatch is whole again... and much better organized
  17. 9. Control your Data, Control your World: Harvesting data
    1. Making the perfect mismatch
    2. Mismatching is all about the data
    3. Break down the Mismatch data
      1. Categories
      2. Topics
      3. Responses
    4. Model a database with a schema
    5. Wire together multiple tables
    6. Foreign keys in action
    7. Tables can match row for row
    8. One row leads to many
    9. Matching rows many-to-many
    10. Build a Mismatch questionnaire
    11. Get responses into the database
    12. We can drive a form with data
    13. Speaking of efficiency...
    14. Generate the Mismatch questionnaire form
    15. The data is now driving the form
    16. Strive for a bit of normalcy
    17. When normalizing, think in atoms
    18. Why be normal, really?
    19. Three steps to a normal database
    20. Altering the Mismatch database
    21. So is Mismatch really normal?
    22. A query within a query within a query...
    23. Let’s all join hands tables
    24. Connect the with dots
    25. Surely we can do more with inner joins
    26. Simplifying ON with USING
    27. Nicknames for tables and columns
    28. Joins to the rescue
    29. Love is a numbers game
    30. Five steps to a successful mismatch
    31. Prepare for the mismatch search
    32. Compare users for “mismatchiness”
    33. All we need is a FOR loop
    34. Finishing the mismatching
    35. Your PHP & MySQL Toolbox
  18. 10. String and Custom Functions: Better living through functions
    1. A good risky job is hard to find
    2. The search leaves no margin for error
    3. SQL queries can be flexible with LIKE
    4. Explode a string into individual words
    5. implode() builds a string from substrings
    6. Preprocess the search string
    7. Replace unwanted search characters
    8. The query needs legit search terms
    9. Copy non-empty elements to a new array
    10. Sometimes you just need part of a string
    11. Extract substrings from either end
    12. Multiple queries can sort our results
    13. Functions let you reuse code
    14. Build a query with a custom function
    15. SWITCH makes far more decisions than IF
    16. Give build_query() the ability to sort
    17. We can paginate our results
    18. Get only the rows you need with LIMIT
    19. Control page links with LIMIT
    20. Keep track of the pagination data
    21. Set up the pagination variables
    22. Revise the query for paginated results
    23. Generate the page navigation links
    24. Putting together the complete Search script
    25. The complete Search script, continued...
    26. Your PHP & MySQL Toolbox
  19. 11. Regular Expressions: Rules for replacement
    1. Risky Jobs lets users submit resumes
    2. Decide what your data should look like
    3. Formulate a pattern for phone numbers
    4. Match patterns with regular expressions
    5. Build patterns using metacharacters
    6. Fine-tune patterns with character classes
    7. Check for patterns with preg_match()
    8. Standardize the phone number data
    9. Get rid of the unwanted characters
    10. Matching email addresses can be tricky
    11. Domain suffixes are everywhere
    12. Use PHP to check the domain
    13. Email validation: putting it all together
    14. Your PHP & MySQL Toolbox
  20. 12. Visualizing your Data... and More!: Drawing dynamic graphics
    1. Guitar Wars Reloaded: Rise of the Machines
    2. No input form is safe
    3. We need to separate man from machine
    4. We can defeat automation with automation
    5. Generate the CAPTCHA pass-phrase text
    6. Visualizing the CAPTCHA image
    7. Inside the GD graphics functions
    8. The GD graphics functions continued...
    9. Drawing text with a font
    10. Generate a random CAPTCHA image
    11. Returning sanity to Guitar Wars
    12. Add CAPTCHA to the Add Score script
    13. Five degrees of opposability
    14. Charting mismatchiness
    15. Storing bar graph data
    16. From one array to another
    17. Build an array of mismatched topics
    18. Formulating a bar graphing plan
    19. Crunching categories
    20. Doing the category math
    21. Bar graphing basics
    22. Draw and display the bar graph image
    23. Individual bar graph images for all
    24. Mismatch users are digging the bar graphs
    25. Your PHP & MySQL Toolbox
  21. 13. Syndication and Web Services: Interfacing to the world
    1. Owen needs to get the word out about Fang
    2. Push alien abduction data to the people
    3. RSS pushes web content to the people
    4. RSS is really XML
    5. From database to newsreader
    6. Visualizing XML RSS
    7. Dynamically generate an RSS feed
    8. Link to the RSS feed
    9. A picture video is worth a thousand million words
    10. Pulling web content from others
    11. Syndicating YouTube videos
    12. Make a YouTube video request
    13. Owen is ready to build a REST request
    14. YouTube speaks XML
    15. Deconstruct a YouTube XML response
    16. Visualize the XML video data
    17. Access XML data with objects
    18. From XML elements to PHP objects
    19. Drill into XML data with objects
    20. Not without a namespace!
    21. Fang sightings are on the rise
    22. Lay out videos for viewing
    23. Format video data for display
    24. Your PHP & MySQL Toolbox
  22. A. Leftovers: The Top Ten Topics (we didn’t cover)
    1. #1. Retrofit this book for PHP4 and mysql functions
    2. #2. User permissions in MySQL
    3. #3. Error reporting for MySQL
    4. #4. Exception handling PHP errors
    5. #4. Exception handling PHP errors (cont.)
    6. #5. Object-oriented PHP
    7. #5. Object-oriented PHP (cont.)
      1. So two big advantages of using Object Oriented PHP are:
    8. #6. Securing your PHP application
    9. #6. Securing your PHP application (cont.)
    10. #7. Protect your app from cross-site scripting
    11. #7. Protect your app from cross-site scripting (cont.)
      1. Validate everything
      2. Built-in PHP functions can help
      3. Data is guilty until proven innocent
    12. #8. Operator precedence
    13. #9. What’s the difference between PHP 5 and PHP 6
      1. More Unicode support
    14. #9. What’s the difference between PHP 5 and PHP 6 (cont.)
      1. OO refinements, XML support, and other changes
    15. #10. Reusing other people’s PHP
      1. Drupal
      2. phpBB
      3. Coppermine Gallery
      4. WordPress
  23. B. Set up a Development Environment: A place to play
    1. Create a PHP development environment
    2. Find out what you have
    3. Do you have a web server?
    4. Do you have PHP? Which version?
    5. Do you have MySQL? Which version?
    6. Start with the Web Server
    7. Apache installation... concluded
    8. PHP installation
    9. PHP installation steps
    10. PHP installation steps... concluded
    11. Installing MySQL
      1. Instructions and Troubleshooting
    12. Steps to Install MySQL on Windows
      1. Download your installer
      2. Pick a destination folder
      3. Click “Install” and you’re done!
    13. Enabling PHP on Mac OS X
    14. Steps to Install MySQL on Mac OS X
    15. Moving from production to a live site
    16. Dump your data (and your tables)
    17. Prepare to use your dumped data
    18. Move dumped data to the live server
    19. Connect to the live server
  24. C. Extend your PHP: Get even more
    1. Extending your PHP
      1. If you’re using Windows, you’re in luck
    2. And on the Mac...
  25. Index
  26. About the Authors
  27. Copyright
O'Reilly logo

Chapter 1. Add Life to your Static Pages: It’s Alive

image with no caption

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 is static and boring

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.

image with no caption

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 brings web pages to life

Note

With a little help from the server!

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.

image with no caption

Dogs in space

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.

image with no caption

A form helps Owen get the whole story

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.

image with no caption

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.

__________________________________________

__________________________________________

__________________________________________

Forms are made of HTML

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.

image with no caption

The HTML form has problems

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.

image with no caption
image with no caption
image with no caption
image with no caption

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.

image with no caption

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).

image with no caption

HTML acts on the CLIENT

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.

image with no caption

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 acts on 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.

image with no caption

Check the boxes for where you think a PHP script belongs:

Client

Server

Both

Neither

PHP scripts run on the server

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.

image with no caption

PHP is a server-side programming language - it runs on a web server.

image with no caption

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:

image with no caption

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.

image with no caption

Use PHP to access 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:

image with no caption

PHP scripts must live on a server!

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.

image with no caption

Web browsers know nothing about PHP and, therefore, have no ability to run PHP scripts.

image with no caption

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.

Get your PHP scripts to the server

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.

image with no caption

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.

image with no caption

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.

image with no caption

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.

The server turns PHP into HTML

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.

image with no caption

Deconstructing Owen’s PHP script

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.

image with no caption
image with no caption

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.

image with no caption

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.

image with no caption

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.

image with no caption

The ?> tag matches up with <?php and closes up a section of PHP code. From here on, we’re back to normal HTML code.

image with no caption

Now wrap up the page by closing out the HTML tags we opened earlier.

image with no caption

A few PHP rules to live code by

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.

image with no caption

Given the variables used in the report.php script, do you see any other PHP rules pertaining to variables? Write ‘em down!

__________________________________________

__________________________________________

__________________________________________

Finding the perfect variable name

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.

The first character must be a dollar sign ($).

Note

Got it!

A variable name must be at least one character in length.

Note

Not counting the $ character, which is required of every variable name.

The first character after the dollar sign can be a letter or an underscore (_), and characters after that can be a letter, an underscore, or a number.

Spaces and special characters other than _ and $ are not allowed in any part of a variable name.

image with no caption

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.

Use all lowercase for variable names.

Separate words in a multi-word variable name with underscores.

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.

image with no caption
image with no caption

Variables are for storing script data

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.

image with no caption

One way to fix the script would be to just assign the exact string we’re expecting to the $alien_description variable, like this:

image with no caption

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?

image with no caption

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?

image with no caption

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 holds form data

$_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.

image with no caption

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.

image with no caption

Brain Power

How do you think the $_POST superglobal works? How can it store multiple values from all those text boxes on Owen’s form?

$POST transports form data to your script

$_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.

image with no caption

The $_POST array is filled with the values the user entered into the form.

image with no caption

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

Note

Similar to the confirmation web page, this email message consists of static text combined with form data.

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.

__________________________________________

__________________________________________

Creating the email message body with PHP

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.

image with no caption

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.

image with no caption

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.

image with no caption

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.

Note

Ouch! This is NOT what Owen had in mind for his Abduction Report email messages.

Brain Power

How would you reformat the plain text email message so that it is easier to read?

Even plain text can be formatted... a little

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 (\).

image with no caption
image with no caption

Newlines need double-quoted strings

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.

image with no caption

Assemble an email message for Owen

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:

  1. The message body. Already done!

  2. The message subject.

    Note

    Anything you want can go here - it’s what will appear as the subject of the email in Owen’s inbox.

  3. The sender’s email address (who the message is FROM).

    Note

    The user’s email address

  4. The recipient’s email address (who the message is TO).

    Note

    Owen’s email address

This is the kind of email message Owen hopes to receive upon someone submitting an alien abduction report.

image with no caption

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!

Variables store the email pieces and parts

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.

image with no caption
  1. The message body.

  2. The message subject.

  3. The sender’s email address (who the message is FROM).

    Note

    All the email information’s gathered and ready to go!

  4. The recipient’s email address (who the message is TO).

Sending an email message with PHP

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.

image with no caption

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.

image with no caption
image with no caption

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.

image with no caption

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 starts getting emails

image with no caption

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.

Owen starts losing emails

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.

image with no caption

Your PHP & MySQL Toolbox

In Chapter 1, you learned how to harness PHP to bring life to Owen’s web form. Look at everything you’ve learned already...

image with no caption

The best content for your career. Discover unlimited learning on demand for around $1/day.