PHP,your,feet,with,hottest,languages,around
Quick Search for:  in language:    
PHP,your,feet,with,hottest,languages,around
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
PHP Stats

 Code: 70,122 lines
 Jobs: 9 postings

 
Sponsored by:

 

You are in:

 
Login



Latest Code Ticker for PHP.
iif() function
By Martin C. Conniffe on 8/16


Dynamic List of Specified Files
By nothing34543534 on 8/15


Active Users (No MySQL) UPDATED! BETTER!
By Brandon Sachs on 8/15


PassGen v 1 stable
By Bogomil Shopov on 8/15


toString v 1.0 b
By Bogomil Shopov on 8/15


Calculating factorials
By Daniel Destro do Carmo on 8/14


AcidicChip's MP3 ID3v2 Tag Writer 1.0
By Chance O. One on 8/14


Click here to see a screenshot of this code!user 2 user messenger 2
By Cornelius Herzog on 8/14

(Screen Shot)

htaccess
By Sven Wagener on 8/13


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!





Affiliate Sites



 
 
   

^ PHP 101

Print
Email
 

Submitted on: 3/22/2002 11:54:35 AM
By: Josh Sherman  
Level: Beginner
User Rating: By 7 Users
Compatibility:PHP 3.0, PHP 4.0

Users have accessed this article 4188 times.
 

(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 langauges 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:

<HTML>
     <HEAD>
          <TITLE>Hello World!</TITLE>
     </HEAD>
     <BODY>
          <? echo "Hello World!"; ?>
     </BODY>
</HTML>

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.

<HTML>
     <HEAD>
          <TITLE>Hello World!</TITLE>
     </HEAD>
     <BODY>

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.

<? echo "Hello World!"; ?>

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 <?php 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.

<HTML>
     <HEAD>
          <TITLE>Greeting!</TITLE>
     </HEAD>
     <BODY>

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.

          ?>
     </BODY>
</HTML>

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.

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

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 12 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
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 PM:kc
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~
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/22/2002 1:45:24 PM:Josh 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
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/23/2002 10:50:15 PM:Gavin
Great start - looking forward to finding some of the others and working through them. Well done.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/14/2002 11:44:13 AM:Ralf Kistner
A great tutorial for beginners! A good site to get PHP, Perl Apache and mySQL support is Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
5/14/2002 11:47:33 AM:R. Kistner
http://www.NuSphere.com (50mb download) Sorry, this is the last part of my previous comment. The linking didn't work.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/23/2002 3:48:42 PM:Bogdan Banea
php or asp? that is the question
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
7/26/2002 9:33:18 PM:Rick
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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/17/2002 12:21:58 AM:StephaneL
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.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
8/17/2002 12:22:52 AM:StephaneL
OOPS I forgot to mention great work on the tutorial, is nice to see people reaching out to help others.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | PHP Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.