Introductory Exercises with PHP
CSCI 2910-001 In-Class Exercise

You should be able to...

This in-class exercise will give you experience with PHP. Specifically, it will cover:

Part 1: Hello, World!

As usual, we will introduce the process of writing and executing a program using the simple application, "Hello, World!". The code shown below is the full "Hello, World!" program along with the PHP to generate the <?xml> tag.

<?php
    print "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Hello, World! in PHP</title>
</head>
<body>
    <h1>
        <?php
            print "Hello, World!";
        ?>
    </h1>
</body>
</html>

Remember from lecture that the PHP scripts are surrounded by the tags "<?php" and "?>" (without the double quotes.) The first PHP script forces einstein.etsu.edu to output the top line of our XML header: <?xml version="1.0" encoding="ISO-8859-1"?>. I would treat this simply as part of the template and just include it in all of your PHP files.

The second PHP script is simply a write print command where the PHP engine on Einstein should replace the script with the output, "Hello, World!" By doing this, the output from the PHP engine should be:

<?xml version="1.0" encoding="ISO-8859-1"?>;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Hello, World! in PHP</title>
</head>
<body>
    <h1>"Hello, World!";</h1>
</body>
</html>

Copy the PHP code (the first section of code shown here) into a text editor of your choice and store it in a file named hello.php.

Part 2: Logging onto Einstein and Running a PHP program

Now that we have a program, let's run it. There are a number of ways to run a PHP script. We are going to begin by running it from Einstein through a browser.

Differences Between Einstein and cscidbw.etsu.edu

The Einstein server works a little differently than the cscidbw.etsu.edu server in a number of ways. First of all, as with cscidbw.etsu.edu, each of you has a folder on Einstein where you will upload your html files and your scripts. This folder is identified with your z-name. When FTP-ing, both Einstein and cscidbw.etsu.edu present this folder to you the same way. With cscidbw.etsu.edu, the root folder where the web server gets your files is the same as the root folder that you log on to.

Einstein differentiates between your root folder on Einstein and the root folder that its web server looks to for files to send to a client. The root folder that its web server accesses is always named public_html and is a sub-folder of your z-name folder.

The second difference is the URL used by each server to access your files. In cscidbw.etsu.edu, the URL of your root folder was simply http://cscidbw.etsu.edu/zabc123/ zabc123 was your user name. Einstein, however, has a slightly different form. It accesses your root HTML directory (public_html) with the URL http://einstein.etsu.edu/~zabc123/. For example, the file einstein.etsu.edu/zabc123/public_html/mypage.html would have the URL http://einstein.etsu.etu/~zabc123/mypage.html.

  cscidbw.etsu.edu einstein.etsu.edu
Root HTML folder cscidbw.etsu.edu/zabc123/ einstein.etsu.edu/zabc123/public_html/
Root URL http://cscidbw.etsu.edu/zabc123/ http://einstein.etsu.edu/~zabc123/

The third difference is that Einstein needs to have its folders and files set with the appropriate privileges before clients can access your files. This is done either by using chmod at the command line or using the chmod function of your FTP application.

Preparing Your Einstein Account

The following steps should allow your account to be accessed successfully from a web browser in order to deliver a PHP file at the request of a browser.

  1. Using WS-FTP or another FTP application, log onto einstein.etsu.edu. (This is the same procedure we used for the SQL labs.)
  2. Under your root directory, create the folder "public_html" (without the double quotes). This can be done by clicking on the button labeled "MkDir" on the server side of the WS-FTP window.
  3. Right-click on the newly created folder. In the content-specific menu that appears, select chmod (UNIX). A window like that shown below should appear.

    WS-FTP Remote File Permissions Window.
  4. Change the permissions such that the owner has read/write/execute and the group and other have read/execute privileges.
  5. Close the chmod window by clicking OK.

Note that you can also change file and directory permissions from the good ole command line using chmod 755 filename.ext.

Now you have created the folder where your HTML and PHP files will be contained. Double click on the public_html folder in order to make it your present working directory. Next, upload your hello.php file to the public_html folder of your Einstein account. The permissions on this file must be changed too. Right-click on the hello.php file on the server side. In the content-specific menu that appears, select chmod (UNIX). Check read/write/execute for owner and read/execute for group and other.

Now we should be ready to access hello.php with our browser. Type in the following URL replacing "zabc123" with your z-name.

http://einstein.etsu.edu/~zabc123/hello.php

If your browser displayed "Hello, World!" as a level 1 heading, then you did everything right.

Debugging PHP

There is another method for running PHP files on the Einstein server. It involves accessing Einstein's command prompt. Okay, I can hear the complaint. "But if we can just use FTP to upload and a browser to view the output, why bother with command line?" In a word, "debugging." First, let's talk about how to do it.

Begin by using PuTTY to log onto Einstein. Using the cd command, change to the "public_html" folder. By typing ls, you should see your "hello.php" file. To execute the file, simply type:

php hello.php

Execution of this file from the command line will result in the text output being dumped to the screen similar to that shown below.

[zabc123@einstein public_html]$ php hello.php
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Hello, World! in PHP</title>
</head>
<body>
    <h1>
        Hello, World!    </h1>
</body>
</html>
[zabc123@einstein public_html]$

To show you the typical result of a PHP error, I went back into the hello.php file and removed the last double quotation mark from the last print statement. This makes it so the PHP engine cannot properly determine where the string to print ends. I then uploaded to Einstein and loaded the script into my browser. Nothing. So I viewed the source and was greeted with the following code:

<html><body></body></html>

This isn't very helpful, is it? Next, I executed the same hello.php from the command line and got the following result.

[zabc123@einstein public_html]$ php hello.php
PHP Parse error: parse error, unexpected $ in /home/zabc123/public_html/hello.php on line 20
[zabc123@einstein public_html]$

Okay, so it isn't a great deal more helpful, but by seeing that the error is on the last line of the file, that would indicate that something was started, e.g., a string, that wasn't closed.

Some web servers redirect the errors from programs into a separate error log located on the server. If this is the case, the only output from the browser may be "Internal Server Error" or "500 Server Error.".

In any case, some of the things to verify when your PHP program does not load properly are:

Part 3: Let's Program!

Between the similarities of PHP and JavaScript and the examples presented in class, we should be ready to program some simple PHP scripts. The program assignment is this: develop a PHP script that uses a for-loop to generate a table with four columns and ten rows in which to display a count (I), its inverse (1/I), its square (I*I), and its factorial (I!). An example is shown below.

I 1/I I2 I!
1 1 1 1
2 0.5 4 2
3 0.33333333333333 9 6
4 0.25 16 24
5 0.2 25 120
6 0.16666666666667 36 720
7 0.14285714285714 49 5040
8 0.125 64 40320
9 0.11111111111111 81 362880
10 0.1 100 3628800

Instead of computing each of these elements, why not let PHP generate the rows for us? What we could do is use standard HTML to incorporate the table elements that are not reptitive, i.e., the starting and ending tags for the table and the tags defining the first row header. For the repetitive components of the table, use PHP to generate the HTML.


In HTML

  • Make starting tag for table
  • Make table header

In PHP

  • Use a for-loop to generate ten rows

In HTML

  • Make ending tag for table

The HTML code to start the table and generate the top row might look like:

<table border="2">
    <tr>
        <td align="center">I</td>
        <td align="center">1/I</td>
        <td align="center">I<sup>2</sup></td>
        <td align="center">I!</td>
    </tr>

The HTML code to end the table might look like:

</table>

The meat of the problem is the PHP code. If you happened to do a veiw source on the table shown above, you'd see that it took 60 sets of <tr> and <td> tags not to mention the 30 values that needed to be calculated. Why not let PHP handle this in a loop? The flowchart below represents the process you might use to create such a table.

Flowchart representing the creation of a table using server-side script.

Using the PHP template shown above, create a file with the appropriate PHP script to execute this, then verify its operation by viewing it. It should match the table shown above.

Part 4: User-Defined Functions

Just like JavaScript, PHP allows the programmer to create functions. There are four important things you need to include with a function: the function's name, any parameters passed to the function from the event handler, the code to execute, and a return value sent back to the calling function using the return() keyword. The general format is shown below.

function functionName(passed parameters)
{
    your PHP code
    return(value to return):
}

The computation of the factorial in our above example although fast is rather clunky looking in the code. Create a function getFactorial($value) that returns the factorial of $value. Use the function to replace the computation within the loop of the previous exercise. As a hint, I've given you the general code below to calculate a simple factorial. Make sure you surround it with the correct function syntax where $value is the passed parameter and the code to return the computed value ($return_value).

$return_value = 1;
for($i=1; $i <= $value; $i++)
    $return_value *= $i;

Part 5: Built-In Functions

PHP has a large number of functions built-in. Just one look at the function reference at php.net will verify that. One of the functions listed under "Mathematical Functions" is pow. The format of the pow function is:

number pow ( number base, number exp )

This function returns an integer equal to base raised to the exp power. Use this function to replace ($i*$i) when calculating the square of $i. Test it to see that it produces the same output.

Once you have the square of $i working, add two more columns to the worksheet using pow: one which calculates 2 raised to the $i and one which calculates $i raised to the 0.5 (i.e., the square root of $i). Be sure to add to the heading to compensate for the additional columns.

Part 6: Include Files

If you decide to reuse a function you've written such as getFactorial(), then you might want to store it in a separate file that can be reference by a number of PHP scripts in different files. In fact, files such as this can be created in order to reuse PHP scripts, functions, and even XHTML code.

Let's store getFactorial() in its own file so that we can use it in other PHP scripts. Open a blank text file and cut and paste the entire getFactorial() function from the file you've been working with into the new file. Be sure to surround the function with the <?php and ?> tags or the PHP engine will treat the code as HTML code and copy it without executing it. Save the new file as myfunc.php in the same directory as the file you have already been working with. (Note: The PHP file extension should be used for the purpose of security. If someone were to try to access your include file directly, the PHP extension would cause the PHP engine to process it before sending it to a client.)

Next, in the location from which you deleted the function in the original file, we are going to copy myfunc.php using the include keyword. The syntax for the include statement is shown below.

include "myfunc.php";

Now upload and execute the code. You should see that it acts no differently. Now, however, with the function as part of an external file, it can be accessed by any PHP script.

The include statement can be embedded in conditional code, e.g., it can be included as if it were a line of code within an if-statement. For example:

if($print_table == true)
    include "myfunc.php";

A second keyword, require, works just like include except for one difference. If the included file is not found, include continues execution after posting a warning while require will terminate the script with a fatal error.