Developer

Tutorial: Getting started with PHP

PHP is becoming increasingly popular as an alternative to Active Server Pages. Join us in a walk-through of a sample program to learn basic PHP syntax and get your first taste of the PHP language.


The PHP Hypertext Preprocessor (PHP) language is as full-featured as a sophisticated programming language, and it’s easy to learn if you have any experience with C, C++, Perl, or shell scripting. This article will give you an overview of syntax and some of the major constructs of the language. It’s geared toward first-time PHP users and will provide everything you need to know to begin developing simple scripts. For a general introduction to PHP, see my previous article, “PHP: An alternative for server-side scripting.”

A simple example
Natively, PHP expects to be embedded within HTML. Take our sample script, favorite.php, which appears below. It begins as a normal HTML page displaying a form, which references itself in its action attribute. The PHP code then checks to see if something was entered, compares that entry to a variable, and gives appropriate output. The page is completed by escaping from PHP and closing out the HTML. (Note that in our example, we’ve set off the HTML code in bold type. We’ve alsoincluded line numbers for convenience only; they should not be included in your code.)

favorite.php1 <html>
2 <head>
3 <title>favorite.php</title>
4 </head>
5
6 <body>
7 <form method=get action=./favorite.php>
8
9 What is your favorite number?  <input name=fav type=text size=4>
10 <br><br>
11 <input type=submit>
12 <br><br>
13
14 <?php
15 # define my favorite number
16 $myfav = 3;
17
18 # check to see if anything was entered
19 if ($HTTP_GET_VARS) {
20
21  # check to see if they entered my favorite number
22  if ($HTTP_GET_VARS[fav] == $myfav) {
23    echo “<b><i>3 is my favorite number, too!</i></b>”;
24
25  # if not...
26  } else {
27    echo “<b>$HTTP_GET_VARS[fav] is your
28      favorite number!</b>”;
29    }
30 }
31 ?>
32
33 </body>
34 </html>

PHP syntax
General PHP syntax is very straightforward and has only four rules:
  • Use the file extension php for Web pages containing PHP code.
  • Escape from HTML into PHP by using an open tag anywhere within your page, as in this line from our example:
14     <?php

You can use any of the four open and close tags shown in Table A.

Table A
Open tag Close tag Description
<?php ?> This is the preferred method.
<? ?> enable-short-tags must be set when configuring PHP during installation for these tags to work.
<script language=”php”> </script> This is for use with Microsoft editors.
<% %> This is ASP style.
Open and close tags for PHP code
  • Add meaningful comments to your code. Again, there are several ways to do this. Table B describes each approach. This line in our sample script shows one method:
  • 15     # define my favorite number

    Table B
    Comment style Example Description
    # # Each of these # comments out one # line of code This is shell scripting style; it hides text to the end of a line or to the end of a PHP block on a line.
    // // Each of these // comments out one // line of code This is C++ style; it functions like #. (This style is preferred over using #.)
    /*   */ /* This will comment out several lines of code at once */. This is C style; it hides all text between /* and */.
    Methods of commenting PHP code
  • End each statement with a semicolon, just like in C or Perl, as we’ve done in our example:
  • 16     $myfav = 3;

    That was painless; now on to the language constructs.

    PHP architecture
    PHP scripts are composed of combinations of constructs that perform an action. The most basic construct, the variable, has a type and a scope, depending on where and how it is defined. While your personal views on readable code may differ, this means you don’t have to define your variables before you use them. In our example, the variable $myfav is automatically detected by PHP to be an integer type:
    16     $myfav = 3;

    Table C shows the types of variables that PHP supports.

    Table C
    Type Example
    Array $myfav[0] = 3; $myfav[“num”] = 3;
    Floating-point number $myfav = 3.001;
    Integer $myfav = 3;
    Object $this->myfav = 3;
    String $myfav = three;
    Variable types

    PHP also has reserved variables. One that appears in our example is $HTTP_GET_VARS. PHP recognizes this array type variable and accepts information from the browser’s user agent. We’ll talk more about reserved variables and variable scope when we encounter them in future examples.

    Another basic part of the PHP language is its control structures. These behave the same as in most languages, particularly Perl or C. Control structures define how to handle expressions and data. The following constructs are available in PHP:
    • If
    • Else
    • Elseif
    • While
    • Do..while
    • For
    • Foreach
    • Continue
    • Switch
    • Require()
    • Include()
    • Require_once()
    • Include_once()

    Notice the syntax of the if and else statements in our example. Each structure begins and ends with a curly bracket. Also note how the statements are nested:
    17
    18 # check to see if anything was entered
    19 if ($HTTP_GET_VARS) {
    20
    21  # check to see if they entered my favorite number
    22  if ($HTTP_GET_VARS[fav] == $myfav) {
    23    echo “<b><i>3 is my favorite number, too!</i></b>”;
    24
    25  # if not...
    26  } else {
    27    echo “<b>$HTTP_GET_VARS[fav] is your
    28      favorite number!</b>”;
    29  }
    30 }
    31 ?>

    A sneak preview of the fun stuff
    It all sounds pretty routine, so how can PHP handle larger, more complicated solutions? With functions, classes, and objects.

    We know from most languages that a function is a logical group of expressions, usually to be referenced multiple times, and receiving and returning standardized input and output. Functions may contain other functions, classes, etc.

    Classes, we know from object-oriented languages such as Java and C++, are groups of variables, expressions, functions, and other classes logically grouped, usually to optimize use of system resources and code reusability.

    An object in PHP is an instance of a class. All data manipulation from a class is done within an object, so no values within the class itself are ever actually changed. Objects can have a defined scope and can be manipulated like any other variable in PHP.
    Want more help learning PHP? Try the following list of resources. And as always, feel free to post your questions below.
    Conclusion
    In this article, we familiarized ourselves with the basics of the PHP language. Next time, we’ll take a more in-depth look at functions, and we’ll write a useful script for collecting form data from a Web site. If you have particular areas of interest, please recommend them for future articles and code samples.

    Editor's Picks

    Free Newsletters, In your Inbox