Watkins Web 2: Blog

Exercise 16: Intro to PHP

Download Exercise 16

Strings, variables, concatenation, conditions.

Update: Solution is now included with the files.

Running PHP files from Terminal.app

Since PHP is a server-side language, you can’t just open the files in a web browser and have them execute the code. For these exercises, we’ll be running the files from the terminal. Here’s what to do:

  1. Download the exercise files to your Desktop and unzip them.
  2. Open Terminal.app and change directories (cd) to the folder that has the files on the desktop. The command you type needs to contain the path to the files, so it will look something like cd /Users/james/Desktop/2011\ 10\ 24\ exercise\ 16 . The simplest way to get the path is to type cd (note the trailing space) and then drag the folder on the desktop right into the Terminal:
    Dragging a folder into Terminal.app
    When you let go, it will spell out the path name for you. Now hit return to change directories.
  3. Type ls (list files) and hit return to confirm that the shell’s working directory contains the files you want to run. You should see a.php, b.php, c.php, etc.
  4. Try running the first PHP file by typing php a.php and hitting return. Now open a.php in Textwrangler and read through it to see how that output was generated.
  5. Any time the screen gets too cluttered, type clear and hit return to start fresh.
  6. For the exercise e, you’ll be using the prompt to input two variables (a name and an age) at the same time that you run the file, so you’ll end up typing something like php e.php James 32.

Further Reading

  • PHP.net, the authoritative reference for PHP definitions, explanations, and actual examples.