Thursday, May 19, 2011

PHP Lesson 1: Hello World

PHP as a Programming Language

First, I need to explain that I'm teaching PHP as a programming language. When PHP was first designed, it was a simple collection of add on tools designed to spice up your personal home page. In fact, Personal Home Page is where the name PHP originally came from. Since then, it has transformed like a caterpillar into a butterfly to become PHP: Hypertext Preprocessor, and while it is still focused on HTML, I believe it to be a very capable language for all sorts of tasks.

What We Aren't Doing: If This Part Doesn't Make Sense, That's OK!

Classic PHP usage involves putting small snippets in the middle of a page of what would otherwise by HTML code, for example:
<p>This is a piece of HTML with a snippet of PHP thrown in to show you that today is <?php echo date('l'); ?></p>
Enclosing small amounts of php code within the <?php ?> delimiters allows PHP to be blended in with an otherwise ordinary .HTML file. But in these tutorials, we won't be using PHP in this way at all. We are going to install the command line version of PHP, and start our source code with the opening <?php tag, but that's it! That tag will never close, because we aren't going to be sending output to a web browser as HTML, we are going to be outputting plain text that we will work with directly from the command line.

Preparing Your Computer to Run PHP

Whether right or wrong, I'm making the assumption that you are running Ubuntu Linux as your Operating System. This is the only part of these lessons where this will make a significant difference, and I'm honestly just too lazy to write out instructions for other platforms right now. PHP is VERY cross platform, however, and if anyone would like to write out corresponding instructions for other platforms in the comments on this post, go for it!

Bring up a Terminal (Applications > Accessories > Terminal) and enter the following command and press ENTER:
sudo apt-get install php5-cli
Even though this isn't a Linux tutorial, I will break down what this means. sudo means "super-user do", which elevates your privileges to administrative level and runs the following command. apt-get install is the command used to install a package, and php5-cli is the Command Line Interface for the latest version of PHP in the 5.x series.

After pressing enter, you will be asked to type your password. As you type it, you won't see anything, but just trust that it is working, then press enter. You will be asked if you want to continue, press Y and enter. Wait while the installation takes place.

Now, we need to make a folder to store our work in for this series of lessons. You're probably already sitting in your home folder. Look at the command prompt and see the ~$ at the end. The ~ is Unix shorthand for "my home folder." Type the following command and then press enter to make a directory called bitslapped, or whatever other name you want to use (just remember to replace the directory name in all future references as well...)
mkdir bitslapped
On the majority of Unix and Linux file systems, folder and file names are case sensitive, so be consistent with how you capitalize if you choose to capitalize the folder name at all. Also, to avoid complications, please don't use folder names or filenames with any spaces in them for the material in these lessons, even though they are technically legal.

Getting Into Your Folder

In order to get into your folder to begin working, this time, and in the future when you open another instance of the terminal, you will need to issue one of the following commands. From now on, when at the terminal prompt, you should always press enter after typing each command and I shouldn't need to tell you to do that any more:

If you are already in your home directory (prompt ending in ~$)
cd bitslapped
Or, if you are somewhere else:
cd ~/bitslapped
If this is done correctly, your prompt will change so that it ends in ~/bitslapped$

We are going to be using two commands repeatedly throughout these lessons, so make a note of these:

To create or edit a file:
nano filename.php
Replace filename.php with the actual filename we're working with.

To have PHP run a program after we've saved it:
php filename.php
For now, use nano to create a file called hello.php by entering the following command:
nano hello.php
Whenever you run nano, if you get an error about nano_history permission denied, just ignore it and press enter. It's not a big deal. When nano opens, you will see a bar across the top of the terminal that says GNU nano (version number) File: hello.php and at the bottom of the screen you will see the [ New File ] indicator, as well as a list of command shortcuts.

When reading nano shortcuts, the ^ means to hold the "Control" or "Ctrl" key, and M- means to hold down the "Meta" key, which on a PC keyboard is the key labeled "Alt" on the left side of the bottom row.

Your cursor is at the upper left of the new text file, so go ahead and enter the following program code, exactly as shown here:
<?php

echo "Hello World";
Once you've entered the above code, press Ctrl+X to exit nano. It will prompt if you wish to save. Press "Y" for Yes and you will be prompted for the filename. It will already have the filename you specified on the command line written in, and if you are still happy with this name (hello.php) just press ENTER to confirm it, and you will be dropped back to the command line.

Now, use the following command to test the program you just wrote:

php hello.php
If everything worked as expected, you will see an output of Hello World followed immediately by the command prompt. There won't even be a space in between. It'll just be mashed together on the same line. Well, that's what we told it to do, but that probably isn't what we wanted. So, we need to edit our program to change this. Re-enter the nano command which can be easily done by pressing the up arrow twice to go thru your command line history, then press enter. Change the program to look like this. nano doesn't support the mouse for editing or moving the cursor. Deal with it, you're a programmer now. The keyboard is more efficient anyway, so use those arrow keys to get to the right place and make the necessary addition:
<?php

echo "Hello World\r\n";
Save it using the same steps as before: Ctrl+X, Y, Enter, then run it again by going thru the command line history to find the php command you previously typed: Up, Up, Enter.

This time you should get Hello World on a line all by itself, and then a separate line containing a new command prompt.

Don't worry about why we put \r\n at the end of our message yet, we will cover that in the next lesson.

So far you've learned how to enter the source code for a program, save it, go back and edit it, and run the program through PHP to see what it does.

Now, I will teach you a few things about what you've entered:

Every php source code file we write will begin with a line containing the magic characters <?php which tell the PHP interpreter that this is indeed a chunk of source code written in the PHP language that it should be able to process.

The command echo means to output the parameter which follows to the "standard output" which in our case is the terminal window screen (also known as the console.)

Because we are specifying a piece of text (called a string) as a parameter to the echo command, we enclose it in quotes. The quotes tell PHP to treat it as text instead of trying to interpret it as another command, as a mathematical number, or as the name of a variable. In PHP, you can use either "double" or 'single' quotes to enclose a string, but backslash codes like \r\n are only allowed within "double quoted strings."

Because some PHP commands can be quite lengthy and may take multiple lines to write out, PHP uses the semicolon character to mark the end of each statement. (A statement is the computer-science term for a single unit of executable code, it means basically the same thing as a "command", and includes any or all parameters that go along with the command.)

Next Post: PHP Expressions & Operators.

1 comment:

  1. To install PHP in Windows you just need to download the binary setup file at: http://windows.php.net/download/
    Then download the installer for:
    VC6 x86 Non Thread Safe
    The installer should put the C:/php/bin into your environment variables so you can use php file.php to run php code from any folder in the computer. To test if its installed type this in the command prompt:
    php --version

    to read what else you can do in the commandline use this command
    php --help
    for instance it says you can use -r switch to run code in the command line without using file. Try this:
    php -r "echo 'Hello World!';"

    ReplyDelete