Introduction to PHP Programming

Getting Started With PHP
By Steve Knoblock

PHP is a language for easily building dynamic web pages. It provides an easier way to accomplish web related programming tasks, which are accomplished only with difficulty in more complex and powerful languages, such as Perl or C. It is ideally suited to the web because PHP scripts live inside web pages right along with the HTML tags and content. For that reason, PHP is called an embedded scripting language. Developers can embed programs in their web pages, making the dynamic. They can treat programs just like web pages. PHP pages can contain both regular HTML and PHP code. This allows you to develop web applications quickly. However, unlike some web scripting languages, PHP makes a clear distinction between sections of PHP code and sections of the HTML document. When the web server fills a request for a PHP enabled page, it first looks through the page content for sections of PHP code and executes any it finds. Any normal HTML sections are passed to the browser without any changes. This means that you can freely mix snippets of program into a web page anywhere.

Why Use PHP?

Here are a few good reasons to choose PHP for enabling interactive content on your web site (besides being open source):

  • You don’t have to know any special commands to compile your program, it runs right in your web browser.

  • You don’t have to know everything there is to know about PHP to start writing useful programs.

  • The data types and structures of PHP are easy to use and understand, PHP knows what you mean and can convert types automatically.

  • PHP is included in most web hosting plans, it can run on Linux and Windows

  • Because it uses similar syntax and constructs, knowledge of PHP can help you in learning the C language.

  • PHP serves as a “wrapper” for many standard C libraries, which are easily compiled into the language giving it the flexibility to respond more rapidly to changes in web technology or trends.

Things you can do in PHP can be done in other languages, but PHP was designed to work in a web context, so things that are difficult or tedious for the applications programmer to “roll their own” in Perl (my favorite language) are easy in PHP. PHP enabled web sites can be deployed with amazing rapidity, due to its being tuned for dynamic pages and database backends.

You don’t have to know everything there is to know about PHP before you can write useful programs. So we will start with a few simple examples.

Embedding snippets of code into a web page has many uses. For example, in an otherwise static web page you may obtain the value of a variable and later use it to dynamically change the content of the page. This PHP example displays the text identifying the web browser on a web page:

<?php 
   $browser = $_SERVER["HTTP_USER_AGENT"];
 
 ?>
 
 <p>You are using the <?php echo($browser);?> web browser.</p>

Your first PHP script: Hello World!

The quickest way to learn PHP is to start using it and see what happens. We’ll start by diving right into the good old “Hello World” script you may have seen when learning other languages. It simply prints “Hello World” to the browser screen using the echo() function.

Each line of code is requires a semicolon at the end. You will probably forget to add the semicolon from time to time and your script will display a syntax error. They are easy to miss. I still leave them off. If you’ve used a number of programming languages, they all do not use the semicolon as their end of line terminating character, so it’s easy to slip up. I sometimes find myself typing C in Perl or Perl in PHP. Perl syntax is very different from PHP, which is more formal with its C influenced functional syntax. For example in Perl you can pretty much drop a regular expression into a statement anywhere, but in PHP you must explicitly make a function call to a regular expression function (ereg() or the Perl-like preg(). What might be natural for a Perl aficionado to code right into their program without thinking, requires putting the regular expression into a function in PHP.

PHP code is delimited by left < and right > brackets. This gives a one line PHP program the appearance of an HTML tag. One liners are often used for outputing content mixed right into HTML.

<?php echo("Hello World!\n"); ?>



<?php print "Hello World!\n"; ?>



<?php print "Hello World!<br>"; ?>

Most people favor the print function over echo(), I think for clarity. “echo” is a term that might cause confusion while “print” is obvious.

The echo() function sends one or more strings of text to the browser for display. Actually, echo is not function but a “language construct” but you do not have to worry about that. It acts like a function. But it does mean that you can save some typing. As a result, the parenthesis are not required. Now, lets take a look at some of the typical PHP syntax in the script. The beginning and end of a PHP code section is marked by angle brackets (less than and greater than signs) followed or preceded by a question mark. The end of each line is marked by a semicolon. The “\n” is a special “escape code” meaning print a new line (or “newline”) that represents a line break in plain text. This is how you would print text to be displayed in a textarea field. For printing to a web page, you need to specify line break tags as the third example shows. Something more appropriate for the web, which leads us into the next topic.

Simple Web application in PHP

“Hello World!” was great for programs that ran on the command line or in a graphical user interface. But the Hello World script needs to be updated for the web, where the basic unit of interaction is the form.

This is the simplest possible form handling script. It accepts a value from one input, the person’s name and then responds by displaying it in the browser window.

hello-web.html

<html>

<body>

  <form action="hello-web.php" method="post">

  <label>Name:</label>

  <input type="text" name="frmName" size="24">

  <input type="submit" value="Submit">

  </form>


</body>

</html>

Because PHP accepts the values submitted from the form and automatically creates variables from the form input names, only one line is needed to generate a response. And because PHP assumes that it is working within the context of a web page, it automatically generates a HTTP header, telling the browser to display any text output.

hello-web.php

<html>

<body>

<p>Hello <?php echo($_POST["frmName"]); ?>!</p>

</body>

</html>

First, PHP outputs a content type header stating the following output is to be HTML. It then sends the P tag and “Hello” to the browser untouched. Once encountering the PHP start tag, it then executes the code until it reaches the PHP end tag. We value from the input parameter “for free” as PHP automatically creates it and initializes it with the value input by the form. In PHP, a variable will be created for any form input value or URL parameter and environment variable that has a value. At that point, it switches back to HTML mode and outputs the exclamation point and the script terminates.

A slightly more complete example than the hello-web script is presented here. It illustrates the concept all in one package without needing a separate html form. This is the basic structure of many browser based applications.

If the form variable does not exist in the CGI enviorment, we know to display the form asking the user for their name. It illustrates the concept all in one package without needing a separate html form. This is the basic structure of many browser based applications.


<body>

<?php

  if(!$_POST["frmName"]){



    // Switch to HTML mode to display form

?>

  <form action="hello-web.php" method="post">

  <label>Name:</label>

  <input type="text" name="frmName" size="24">

  <input type="submit" value="Submit">

  </form>

<?php

  }

  else{

?>

<p>Hello <?php echo($_POST["frmName"]); ?>!</p>

<?php

  }

?>

</body>

</html>

At the very end we switch back to PHP mode just to close the else clause. This may be overkill in this small application, but this kind of mode switching part of the php-way. You could use echo or print commands and forget the mode switching. Which to use depends on the situation and your mood. :wink:

This script hints at how “finite-state machines” implemented as switch/case statements are at the core of many scripts that handle web based interactions. This one has only two states: invite the user to submit data and post submitted data back to the web. So an IF statement is sufficient.

Dynamic Content

I’m sure you’re interested in doing more with PHP than saying hello to the world. Otherwise, you probably would not be here reading about an HTML-embedded scripting language. You want a script that does something useful. Let’s go deeper into PHP by writing a Tip of the Day script. It will introduce several new functions and concepts, but you do not have to understand them all at once. It also offers an introduction to working with the file system.

<?php

  srand((double)microtime()*1000000);

  $tiplist = file("photo.tips");

  $ntips = sizeof($tiplist);

  $rtip = rand(0,$ntips-1);

  $tip = $tiplist[$rtip];

  echo $tip;

?>

The first line of the script opens a file called photo.tips (remember, Unix does not care about so-called “file extensions” found in Windows, so we don’t need “.txt” at the end to identify it as a text file). There is no need to write anything to the file because we will just be reading and displaying a line of text from it. Using the file() function, each line of the file is read into the array $tiplist. We do not have to specify any file handles because the file() function takes a filename as an argument and returns an array as a result… Each element of the array corresponds to a line of the file. The newline character is still attached to each string in the array. The tips file contains several tips, each on a line.

Next, we find the number of elements in the tips list array by using the sizeof() function. It returns the number of elements in an array. The following line generates a random number between zero and the number of tips read from the tips file. rand(n,m) returns a random number between n and m (we must specify a range between 0 and 3 if there are 3 tips because the range is inclusive). Because PHP arrays start a zero, we set our random number to between zero and the number of tips minus one. The randomly generated number is used as an index into the tips list. The script randomly selects a tip from the list using this index. The text of the selected tip is then output to the browser through the echo() function. Since we already have the string in a variable, we don’t need any quotes around it.

This script nicely illustrates the PHP philosophy of working within the what is called “the HTML-context.” If you notice, the script is inside the HTML code, and that the script is a web page that can be placed anywhere on the site. Because PHP scripts generate output after a “Content-type: text/html” MIME header is output to the browser, any output they generate will appear in the browser window. This also allows PHP code to be directly mixed with HTML code on the page. A special cgi-bin is unnecessary for PHP scripts.

Sponsor our Newsletter | Privacy Policy | Terms of Service