On the Web :: Employment :: Jobs :: Training :: Tutorials
SkillsPride
ONLINE COURSES
Back to Learning Zone Index
INTRODUCTION TO PHP
What exactly is PHP?

     PHP is a server side scripting language bearing similarities in structure to C, Java and Perl. PHP started as one man's (Rasmus Lerdorf) personal project to make embedding more complex code in HTML a lot easier and has grown into being a full-fledged scripting language. It is growing in both popularity and becoming more powerful as a language and version 4.0.2 has just been released. Programmers met in early 2000 in Tel Aviv, Israel to discuss the organizational direction of PHP as well as creating even better functionality with the increasingly popular mySQL database. Depending who you talk to the name PHP can stand for several different things, but today it is most commonly known as: Hypertext Preprocessor. The home web site is http://www.php.net/.
     zzzzzzzz ...
     Ok have I put you to sleep yet?
     Seriously, I would like to try and have you come away with something useful you can take back to your websites and use. So if you promise not to fall asleep, I'll promise to try and not make you sleepy and explain why you should be interested in PHP and show you over a series of 16 courses how to do some really cool and useful things that you'd normally have to pay a programmer several hundred to several thousand dollars to do for you. In this article we need to do a little maintenance first.
     You don't have to be a genius!
     Before you run clicking for the back or exit button, understand that programming isn't necessarily some huge insurmountable process. I like to think of any project in a much smaller sense and right now when I say that I'm going to teach you fundamental programming in PHP over a series of 16 courses that might instill panic in a few webmasters or seem like an insurmountable task to others. I have been doing programming for roughly 20 years and I can safely tell you that I am still very much learning, so the process of learning never stops, nor should it.
     First, let's break this down into a series of logical issues and this is the same way you might go about dissecting a programming project.

I. What tools do I need for the project?
II. What programming language or languages will work best for the project? HTML  JavaScript, PHP, Perl, etc. 
III. What knowledge do I need to possess?
IV. Where do I start?
     Every time we look at a programming tutorial we'll start with this fundamental concept. There are some basic tools that you can't do anything without and the best part is that everything you need you can obtain for free, including the server to run PHP on your local PC! Items II-IV above we will deal with when we get into our first programming project in PHP. You will need the following tools for every project we discuss.

I: TOOLS NEEDED FOR PHP SCRIPTING:
     1. You need a text editor of some kind to do scripting. Some people laugh when I tell them I use the free one that comes with Windows: Wordpad. However, I also have purchased several commercial text editors and somehow I always return to Wordpad for it's simplicity. I guess I like working with white space better than having a bunch of bells and whistles. You can use Notepad also, but Notepad limits the size of documents, so probably not a good idea to get used to using that. Feel free to post your suggestions for great text editors for other students in the Week 1 forum
     2. You need a UNIX or NT host (I will commonly refer to using a host as an externalenvironment) or by using your local environment (your PC you are likely reading this from now) with the PHP source compiled. While these tutorials will be a great springboard for you to write code, if you don't have a place to actually execute the code you won't actually be able to do anything with the code you write. You can set up your own local webserver in Windows and use the free Xitami webserver, by visiting http://www.imatix.com/html/xitami/index.htmOn that page you will find detailed instructions on setting up your own free local web server in Windows. I personally do not use a local environment, but I have several friends who use the Xitami webserver with PHP and speak highly of it. Instead, I use several UNIX hosts who have PHP and I hope you'll encourage your hosts to make PHP available for you. If you'd like a list of hosts that currently support PHP, at the PHP website there is a cool search engine you can use to actually choose what features you want: http://hosts.php.net/search.php3   Below I give you a simple way to test if the host you have is running PHP. One final note on whether to use UNIX or NT hosts when programming PHP, I am but a newbie in the woods to the world of scripting PHP on an NT host, so most of my examples will focus on PHP for UNIX servers. I am in the process of setting up an NT host with PHP so I am hoping to share code examples for both environments when possible.
     3. If you are using external environment you will need an FTP editor. You can use fancy HTML editors like Front Page, but I would not recommend this. These editors have a habit of introducing "helpful" code in irritating and in some cases invisible places like carriage returns, extraneous HTML, double quotes, etc, to your scripts that can cause immeasurable problems. There are many good FTP editors out there and even a few free ones like http://www.smartftp.com/ that will allow you to drag and drop files. You need an FTP editor that will allow you to change permissions of files. If you have never set permissions on a CGI file or directory, you can usually accomplish this by right clicking on the file or directory in your FTP editor and a menu should pop up that says permissions or chmod or something like that. If the editor you are using doesn't seem to have this capability (most do) consider downloading one that does.

How do I know if my host has PHP?

     The easiest way is to consult your host's website or call them directly and ask, but if you have one of those hosts where reaching them is difficult, then you can run a simple test using PHP code. TYPE the following code into your text editor (sometimes CUT AND PASTE adds troublesome formatting to the code when going from HTML to your text editor, so always type my examples directly into your text editor):

<?
// Does my host have PHP, and if so, what version?
printf("Your host is running PHP version %s", phpversion());
?>

Example of output:

Your host is running PHP VERSION 3.0.7

     Now save the above file in your text editor as phpversion.php3 or phpversion.phtml. Note: you can often use php3 or phtml or php synonomously as an extension to identify a PHP script.
     APACHE USERS: if your site is hosted on an apache webserver the default extension is .php in apache.
     FTP this file in ASCII mode somewhere on your webserver. Some FTP editors will have a mode called "auto" to determine whether the mode is ASCII or BINARY. I would not recommend using "auto" mode, instead override the setting and make it ASCII. For those Perl people in the audience, the good news is this file does not have to be in a cgi bin, nor do you have to set any special permissions for it. Now goto your browser and call the script by typing it from the browser line. If you have PHP you will see the version number that is installed on your server.
     If you'd like to see the modules and settings that your host has installed for PHP on your server in a neat table you can use the following code:

<? phpinfo(); ?>

PHP code tags

     As you could see in the above example we used <? and ?> tags. While these might seem foreign at first, this is how you tell the interpreter where your php code begins and ends. Similar to your <HTML> and </HTML> or <CENTER> and </CENTER> tags in a document, you cannot write working PHP code without enclosing your php code inside these every time. There are other valid formats you can use if you don't like the more simple <? and ?>, you just need to make sure you use the correct corresponding group. For example using <? to start the code and </script> to end it would produce undesirable results.

<?                                    <--- this indicates the starting of php code (group 1)
<?php                              <--- another way of starting php code (group 2)
<script language="php">  <--- another way of starting php code (group 3)

?>                                    <--- this indicates the ending of php code (group 1)
php?>                              <--- another way of ending php code (group 2)
</script>                          <---- another way of ending php code (group 3)

     Therefore we could have also written the code above using the more common group 3 php tags as:

<script language="php">
/* Does my host have PHP, and if so, what version? */
printf("Your host is running PHP version %s", phpversion());
</script>

     You do not have to separate the lines of code, as I did above, you can put everything on one line like this:

<? PHP CODE GOES HERE ?>

Adding Comments To Your Code

     While you may understand the code you are writing it is a good idea and considered good practice to comment your code. Although it is entirely optional, I will adopt this practice throughout our tutorials so you can better understand what the code is doing. I did so in the above example. There are two different ways you can add comments.

C type method:

/* your comments
can go here and can
be on multiple spaces
and when you are
finished writing notes
don't forget the closing
*/

// comments can only go on one line, no closing is necessary

     Refer to my example above and you'll see I used the // method of adding comments to the code, since my comment only took up one line. It doesn't matter which method you use for comments so long as you remember that if you use the C method you must close the comment tag ( by using */ ) and if you use the // method that you keep the comments on the same line. Remember that comments are optional yet a good idea for producing readable code. While you write the code it is fresh in your mind, but often times several months later when you go back to review it will not be.

Using built-in PHP functions

     PHP has a lot of useful functions built-in to assist you in coding. Things like printing to the browser are taken care of by using the function print. In our example above we used the slightly more complicated printf function to print the version of PHP to the browser in a certain format. Most every programming language starts you off by printing the rather useless: "hello world" example. I would now recommend that you go download the PHP function library. You can do this by visiting http://www.php.net/docs.php3 and downloading the big zip file (1500kb). The PHP function documentation for the print function looks like this:

print
Description
print -- output a string
print(string arg);
outputs arg

     This is commonplace for programming reference manuals that they speak in technobabble that irritates even programmers. The only reason I suggested you download this is that you will need to have this as a reference material down the road. I will give you a much friendlier explanation than this for the functions we use, but I wanted to show you where the built-in functions are explained. You should further note that not all functions listed may be available in your version of PHP. For the purpose of our courses I will try to only use functions that are in lower versions whenever possible so the examples will work on your version of PHP. Now before I can give you my friendlier explanation of the print function, it requires understanding what a string is.

What are $strings?

     A string is a container that holds text which can be made up of letters, numbers, words or entire sentences. Strings can contain integers (whole numbers like 1,2,3,4,5) or floating-point numbers like (1.5, 2.67, 3.9993, 9.0), or text. A string name is preceeded by a dollar sign $ to show it is a string. Numbers are not required to be enclosed in quotes, but alphanumeric characters are (IE. "7 lessons"). You can assign a value to a string by using the equal sign =

$myname = "TDavid";
$my_website = "tdscripts";
$myfavoritenumber = 7;

     String assignments must end with a semi-colon. Valid string names begin with an letter and can contain numbers or the underscore symbol _   Case sensitivity matters in the Unix world, so $tdscripts and $TDscripts would actually be two different strings.

Valid String Names
$tdscripts
$Script_School
$Visit_my_tech_radio_show_every_friday_at_2pm

INvalid String Name
$2pm_PST         <---- starts with a number

     Tip: Use string names that identify what you are storing. For example it may take a bit less space to use strings like $a = "123 Any Street"; but it is much easier to understand code when you have problems if you use something like $address = "123 Any Street";
     Now that you understand what strings are let's go back to a more friendlier explanation of what the print function does. It prints the contents of a string to the browser.

<?
print("Yippie! My host is running php!");
?>

     Could also be written by assigning the text to a string like this:

<?
$comments = "Yippie! My host is running php!";
print($comments);
?>

     Notice that when you print a string you do not need the quotes surrounding the string, and that in PHP you enclose the string you want to print in parenthesis. Now if you look back at the php manual definition for the function print you will see that arg stands for argument. An argument is what is passed inside the parenthesis to a function. In this case the contents of the string is its argument. Is the technobabble a littler clearer now?
     A technical aside for the purists in the audience: in terms of being useful, why would you ever want to use the second example above? Let's say you are building a script that will be translated into multiple languages. Rather than having to go through all your code and changing the English text strings inside the print functions to say Spanish instead, you could go to one section where a bunch of text strings are being assigned and easily make the translation in one section of code.
     Well that covers some very basic terrain with PHP. With these basics you should now know the tools necessary to create a PHP script (and where to obtain them), and how to store information in strings and print strings. Next week we'll dig in and I'll show you how to create a picture of the day script in PHP that you can freely use on your websites. But first ... let's give you your very first coding assignment:

TO-DO ASSIGNMENT #1: Write a script to store and print your name (nick) and at least one favorite url to the browser using variables to assign them. Make the variable names conform to the rules explained above and use comments in the code explaining each line of code. Cut and paste your code to the Week 1 forum to share with others in the appropriate "To-do Assignment #1" folder.

Need help with your assignment or have questions about the first week's course?

TDavid is co-owner, programmer and webmaster for several sites devoted to programming including his own http://www.tdscripts.com/ He has done custom programming in various programming languages for companies all over the world. Every Friday at 2pm PST you can catch his weekly radio show dedicated to the technical side of webmastering and programming at http://www.scriptschool.com/radio