Important alert: (current site time 4/20/2014 2:23:53 PM EDT)
 

article

PHP 101

Email
Submitted on: 3/22/2002 11:54:35 AM
By: Josh Sherman  
Level: Beginner
User Rating: By 15 Users
Compatibility: PHP 3.0, PHP 4.0
Views: 35135
author picture
(About the author)
 
     Get your feet wet with one of the hottest web languages around, PHP!

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

So you want to be cool like me and utilize the power of PHP when developing web sites? Then you've come to the right place. This tutorial will give you a basic introduction to PHP, as well as enlighten you to some of the commands that you can use.

If you're curious to what PHP stands for, you're going to be a bit disappointed with my answer. PHP stands for PHP: Hypertext Preprocessor. Now that you're confused, let me explain what PHP is. PHP is a server-side, cross-platform, HTML embedded scripting language. What's that mean to you? It means you can create dynamic web pages!

Before you can start using PHP, you need to find a host that supports PHP, or set it up yourself. PHP is free, and available from http://www.php.net/, along with documentation, functions lists, bugs, et cetera.

Once you have a server at your disposal, you will need a really expensive development environment to code in. Oh wait, we're not talking about a Microsoft product here. All you will need for PHP is a basic text editor. Notepad or vi will be sufficient. As a matter of fact, those are the only tools I use for coding PHP.

Now on to the fun part, hope you're ready to build your first PHP-enabled page.

First, create a new file, and name is "helloworld.php". Note the .php extension. PHP requires files to have a .php, .php3, or .php4 extension. Usually .php will due just fine.

Now I hope you didn't think I was going to skip the infamous "Hello World!" example. Now that you have your file, open it up in your editor, and type in the following code:



Hello World!




As you can see, I'm a stickler for indenting, but this is not necessary for PHP.

Once you have the code typed up, go ahead and save the file, upload it to your host, and place it in the appropriate directory on your system, and pull it up in your web browser.

The output should be:

Hello World!

Congratulations you've successfully built your first PHP page. Simple enough, huh? Well that's just a small taste of what PHP can do, and is far from utilizing PHP’s full potential.

Okay, so you've made your first page, big whoop, now it's time to learn what the hell we did. I'm going to go line by line and explain what each bit of code means and does.



Hello World!

The first part of the page is simply HTML tags. If you don't know what that does, then I'm sorry for you, and I advise you stop reading this tutorial now and learn some basic HTML.

This little bit of code is out only PHP in the entire document. The nice part of PHP is that it gives you the ability to mix and match HTML and PHP to produce a web page.

The , indicates the start of a PHP tag. Depending on how PHP is set up on your server, you may or may not need to use instead of . To close your PHP tag we use ?>. PHP tags don't have to be a single line like our page, you can span it over multiple lines, to include more complex code such as if statements and loops.

We've now covered the beginning and ending PHP tags, now we're going to analyze what we have in between them. echo is the command used to print information on the display. Depending on how much you need to display, echo might not be the best choice. For single lines, echo is wonderful, but if you have 2 paragraphs, it may just be better to close the PHP tag and simply have the paragraphs in the HTML portion of the site. echo allows up to display not only plain text that is enclosed in quotes, but variables as well.

echo $blah;

That would output the contents of the $blah variable.

The last portion of the expression is the ;. All lines in with ; unless they are a part of a conditional expression like an if structure. The rest of the code is just basic HTML to close the BODY and HTML tags, nothing of real importance.

So, you've gotten one page under your belt, and have a basic understanding of how PHP works, and how to use the echo statement. Next, we're going to go over the if statement, and how to create something a bit more dynamic.

Like before, I want you to create a new file, but this time name is "greeting.php". This time, I'm going to walk through the code with you step by step and explain it as we go along.



Greeting!

Just like before, we're going to start our page with the basic HTML code, including a title for our site.

$current_hour = date ("H");

Here we opened up our PHP tag, on the next line, we are assigning a variable. The variable is named $current_hour. Variables in PHP start with $, and are case sensitive. The value we are assigning to the variable is date ("H").

Welcome to the world of functions! date() is a predefined function in PHP that is used to provide with the time and/or date. In this instance, we're pulling the hour of the day, in the 24-hour clock format. The value it assigns to our variable will be 0-23. At the end of our line, we have our semi-colon as usual.

if($current_hour<"12") {
echo "Good Morning!";
}

if structures are one of the most useful pieces of code in which you can utilize. In this instance, we are determining if the $current_hour variable is less than 12. If it is less than 12, then we are displaying the words "Good Morning!" and then the structure is complete and it moves on.

if structures are fairly simple, they start with if and within the parentheses, you put in your condition. Your condition can be one of six different operators, == (is equal to), != (is not equal to), > (is greater than), < (is less than), >= (is greater than or equal to), <= (is less than or equal to).

After we have the if structure put together, we end the line with a fancy bracket, {. The { tells us where to put action code. After we put in the code that will be executed when the condition is met, we end it with the other bracket, }.

if($current_hour<"20" and $current_hour>="12") {
echo "Good Afternoon!";
}

This is out second if structure, and incidentally, a little more complex. It contains 2 conditions that have to be met before the result is executed. We separate the conditions with and (you can also use or depending on the situation). If $current_hour is less than 20, and is greater than or equal to 12, then it will display "Good Afternoon!".

if($current_hour>="20") {
echo "Good Evening!";
}

The last of our if structures in this page. This one is very similar to our first as it determines if $current_hour is greater than or equal to 20, and displays "Good Evening!" before stopping the PHP tag.

?>

Just closing tags. It ends out PHP tag, and the BODY and HTML tags.

All finished, all we need to do is launch the web site and check out the result. Depending on the time of day, you will get a different response, either Good Morning!, Afternoon! or Evening!.

If you've done any kind of programming in other languages, you know that my use of 3 if structures could be refined. That leads me into my next example. No need for a new file this time, we are going to modify "greeting.php" that we just finished up.

Find the following snippet of code, highlight it, and delete it.

if($current_hour<"12") {
echo "Good Morning!";
}

if($current_hour<"20" and $current_hour>="12") {
echo "Good Afternoon!";
}

if($current_hour>="20") {
echo "Good Evening!";
}

We are going to rewrite that section of code, and utilize nested if structures.

if($current_hour>="20") {
echo "Good Evening!";
} else {
if($current_hour<"12") {
echo "Good Morning!";
} else {
echo "Good Afternoon!";
}
}

That will do the same thing as our previous code, but instead of 3 separate if structures, we use 2, and make use of else. else is part of an if structure, which executes a different set of code if the condition is false.

the first if structure checks to see if $current_hour is greater than or equal to 20. If it is, then it displays "Good Evening!". If it isn't then it executes another if structure (our first nested if). That next if structure checks to see if $current_hour is less than 12, and if that is true, then it displays "Good Morning!". If the nested if structure is false, then it displays "Good Afternoon!".

Within the { and } of an if statement, you can put virtually any code you want in there, and it will execute it.

That should do it for using the if structures to create dynamic content. Next on the agenda is to teach you about cases, and query strings, so that you can produce truly dynamic content, instead of just displaying greetings to your visitors.

This next page is going to be called "dynamic.php". Like the first example, I'm going to give you all of the code at once, and then explain it step by step.



switch ($pageid) {
case "1":
echo "Page 1";
echo "Page 1 content goes here.";
break;
case "2":
echo "Page 2";
echo "Page 2 content goes here.";
break;
case "3":
echo "Page 3";
echo "Page 3 content goes here.";
break;
default:
echo "Page $pageid doesn't exist.";
break;
}
?>

Once you have that typed up the code, and put it on your server, bring up the page in your web browser. It should display "Page doesn't exist." What the case statement does, is it allows you to do a large if statement, but not as complicated. The cases are started off by switch ([variable]) {. This determines what variable to check for the cases. In this instance, we are using the variable $pageid. Now each case is defined as case "1": - case "3": and then default:, to represent all over instances.

So we ran it, and it told us the page didn't exist. Why? Because we didn't tell it what page to display, and because of that, it went with the default. This is where the query sting comes in to play for us. I'm sure you've seen a query string in your life time, and if not, oh well, I'm going to explain it anyway.

Pull up the web browser we displayed the page in previously. After the dynamic.php, we're going to append ?pageid=1 to the end of it. Go ahead and press enter to display that page. This time, it should display "Page 1 content goes here." Now change the pageid=1 to pageid=2 and then to pageid=3. It should display the appropriate pages for you.

What's all this mean to us as web developers? It means you can have a single file, and host a million different pages off of that file, and make calls to them by a variable in the query string. You can also have multiple variables in the query string, to make your page even more dynamic. The variables can be named virtually anything you want, and are formatted together like this:

index.php?section=essay&page=2

We use the ampersand to separate the variables in the query string. As you can see from the example, you can call the section that you want, and then the page number of that section all from the query string. Once you start to utilize such tricks as this, you will never goes back to coding flat HTML pages.

The other new command is break. break simply stops the execution of a structure, such as our switch, and continues on. We use break at the end of each case so that it doesn't execute all the cases. If we didn't include the break's, and we ran the page with the query string ?pageid=1, then our output would be: "Add content for page 1Add content for page 2Add content for page 3Page 1 doesn't exist. " Not really what we wanted, so we'll stick with the breaks. If you have nested structures, and need to break out of say, 3 of them, you could use break 3; and it will break all 3.

It's almost time to wrap up this tutorial, but I would like to go over a few other simple commands that will help you on your way. First, we have require() which allows you to add text from another file, kind of like server side includes. Unlike date(), require() is not a function in PHP, but a language construct, and doesn't return any value. One great use for require() would be in your cases from the previous code. Instead of adding echo this and echo that, you can have a separate file with all of the code, and then simply have require ("page1.php"); which will pull that data into your page.

The last command is exit() which again, is a language construct. exit() will terminate the script and output a message if you want it to. This command is good for detecting an error and halting the script. You can either use exit; to halt it, or something along the lines of exit("Halting Script"); to halt it and display "Halting Script" to let the user know what's going on. The nifty part about exit() is that it has an alias. That means there is another command that will do the same exact thing, which is die(). You can use the two interchangeably.

So now you have a basic understanding of how PHP works, and a small knowledge base of commands you can use, along with the basic flow and logic of a page. If you are interested in learning more on your own, check out http://www.php.net/ which has a listing of all the commands, and a full online manual. If that's not enough for you, then search the web, there are quite a few web development sites out there, most of which have information on PHP. If you're too lazy to search on your own, then hold tight, there will be more PHP tutorials in the near future.


Other 17 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

3/22/2002 1:28:04 PMkc

This is really good.. well written. :)
two thumbs up!
Anywho...
Just thought i'd share some insight for everybody that's just starting out...

I too went to http://www.php.net and don't get me wrong, it's a great site. Although it felt to me as if it was written in greek. That is.. how to set it up. I'd advise, for all the window users, to go to downloads.cnet.com and search for phptriad.

this is a really good apache server with php already configured. It's a 10mb download but it's well worth it.
~kc~
(If this comment was disrespectful, please report it.)

 
3/22/2002 1:45:24 PMJosh Sherman

good call, i'm not sure of the difficulty level of setting up PHP on a windows box, in linux all we do is extract the package, run ./configure, make, and make install pretty simple ;)

gracias for the feedback
(If this comment was disrespectful, please report it.)

 
3/23/2002 10:50:15 PMGavin

Great start - looking forward to finding some of the others and working through them. Well done.
(If this comment was disrespectful, please report it.)

 
5/14/2002 11:44:13 AMRalf Kistner

A great tutorial for beginners! A good site to get PHP, Perl Apache and mySQL support is href=
(If this comment was disrespectful, please
report it.)
 
5/14/2002 11:47:33 AMR. Kistner

http://www.NuSphere.com (50mb download)

Sorry, this is the last part of my previous comment. The linking didn't work.
(If this comment was disrespectful, please report it.)

 
7/23/2002 3:48:42 PMBogdan Banea

php or asp? that is the question
(If this comment was disrespectful, please report it.)

 
7/26/2002 9:33:18 PMRick

This seems simple enough but it will not run on Windows (all I know) 2000. I have no idea why and just spent 2 hours searching the web to find an answer. Please include a blurb for us pathetic Windows users to get started in PHP. Thank you.
(If this comment was disrespectful, please report it.)

 
8/17/2002 12:21:58 AMStephaneL

I am an avid windows user while most of my friends have wandered over to open source. I learned that linux is for people that have a need for headaches and long sleepless nights (if you dont believe me read up on sendmail :) )Everything you will ever need has been ported to win32, but to answer the question above, ASP is a nice language but sloppy and hard to understand compared to PHP. So in my humble opinion PHP is the way to go.
(If this comment was disrespectful, please report it.)

 
8/17/2002 12:22:52 AMStephaneL

OOPS I forgot to mention great work on the tutorial, is nice to see people reaching out to help others.
(If this comment was disrespectful, please report it.)

 
9/2/2002 5:15:44 PMMehdi Hanbali

why use php when we have perl :)
(If this comment was disrespectful, please report it.)

 
9/2/2002 5:16:38 PMMehdi Hanbali

perl is "the manly coders" language. uh, i mean "scripting language"...
(If this comment was disrespectful, please report it.)

 
9/14/2002 5:41:18 AMDarryl Porter

Compared to PHP, perl should only be found around necks
(If this comment was disrespectful, please report it.)

 
10/23/2002 6:31:31 PMDodger

Excellent, Thanks Josh!
(If this comment was disrespectful, please report it.)

 
10/24/2002 9:34:39 AMJosh Sherman

we'll to clean up all this talk of perl and asp, here's my view on it all. i've learned both asp and perl, and have been very unhappy with them both. asp is too much like visual basic, and being a linux guy, visual basic or anything m$ isn't my thing. as for perl, i have no real beef with perl, i simply don't feel it was meant to go as far as it has, i.e. cgi scripts and such. perl has it's uses, but most of the things i've used it for, i replaced with using shell scripting. php is my love, and that's that. if you don't like it, then don't code in it. thanks
(If this comment was disrespectful, please report it.)

 
11/19/2002 6:20:17 PM

I myself enjoy php to the max and for you windows users heres a nice place to get all you need for a functioning webserver on windows, href=
(If this comment was disrespectful, please
report it.)
 
11/19/2002 6:21:34 PM

bah it cut me off but windows users go to phpdev for windows
(If this comment was disrespectful, please report it.)

 
8/19/2003 5:39:06 AM

I'm trying to do the tutorial . In the beginning (after you set up a php file on notepad) it says to type in code but nothing comes up
(If this comment was disrespectful, please report it.)

 
9/16/2004 5:18:51 AMCor!

PSC have changed their submission formatting, so some of this tutorial's code is no longer visible. Just right-click the page, select View Source (if WordPad is your default text editor, press CTRL+F, type this text "IN THE FOLLOWING CODE:", hit search, and you will see the start of the missing code. 5 globes from me.
(If this comment was disrespectful, please report it.)

 
12/15/2005 8:27:36 PMBrian

Josh Sherman, I've setup apache with php5 on my winxp box, and it was quite easy!
(If this comment was disrespectful, please report it.)

 
5/11/2006 11:04:52 AMGilbert

I loved the tutorial, and thinks its a great work by Josh.

Thumbs up, Josh.

Gilly
(If this comment was disrespectful, please report it.)

 
11/4/2006 5:38:20 AMPatrick

I would like to read a code of an admin section to update a web site
(If this comment was disrespectful, please report it.)

 
3/28/2012 3:34:17 AMmart24

No file to download :(
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.