Exercise 16: Intro to PHP
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:
- Download the exercise files to your Desktop and unzip them.
- 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 likecd /Users/james/Desktop/2011\ 10\ 24\ exercise\ 16
. The simplest way to get the path is to typecd
(note the trailing space) and then drag the folder on the desktop right into the Terminal:
When you let go, it will spell out the path name for you. Now hit return to change directories. - Type
ls
(list files) and hit return to confirm that the shell’s working directory contains the files you want to run. You should seea.php
,b.php
,c.php
, etc. - 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. - Any time the screen gets too cluttered, type
clear
and hit return to start fresh. - 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.