A Reminder about CGI

The Common Gateway Interface, or CGI, is the standard method for web servers to interact with programs on the host. These programs act as the middleware or application servers and produce the web content you see when surfing the internet. CGI programs, when viewed via the web, are nearly indistinguishable from static HTML files, this is because these programs are generating HTML!

CGI, or the Common Gateway Interface, is common because it is not specific to any operating system or language. Output is generated at runtime when the program is executed by the web server and the output (STDOUT, Standard Output) is redirected from the web server to the client browser.

We use forms on the web to allow the client to input information and submit that information to the web server to be processed. This data is processed by (forwarded to) a CGI script/program residing on the server which takes in the input, processes it, and returns the output. Scripts normally receive this information via either the GET or POST methods from the various forms. Remember that with the GET method information is encoded directly into the URL, example:

http://www.cs.usna.edu/cal/view.php?event=seminars
And this allows us to inform the server of input, possibly without using a form at all.

A better way forward

Wouldn't it be nice if we could place our scripts along side our HTML, and the web server could execute the portions of the code that it could on the server side, while passing the information that it didn't need to work with directly to the browser!

Imagine the following file residing on the server:

<h5>Welcome to the our amazing website</h5>
<p>
  Here at amazing.com, we realized it was easier to process
  information in the middle of our HTML.
</p>
<p>
  Imagine if we wanted to make a nice greating, and put your name in
  the HTML directly we could, by doing something like:
</p>

<p>
  Welcome

  <tag-to-tell-server-to-do-work>
    // And we could now have code that would be processed on the *server* side
    // and not just forwarded to the browser.

    // Imagine the following pseudo-code:
    $user = database.retrieve.username();
    echo $user;

    // Since CGI is all about outputing text via stdout, why not just
    // inject it directly into our HTML?
  </tag-to-tell-server-to-do-work>

  <!-- We are now back in HTML mode again,
       and everything will just be sent directly to the browser -->

  It's really nice to see you again.
</p>

Wouldn't this design solve alot of our problems, we could have both HTML and executed code as part of a single page, seamlessly transitioning from one to the other. Switching from just forwarding the raw HTML to the browser, seamlessly to computing something and sending that new data on the fly to the browser.

PHP

PHP is that server-side scripting language which meets the requirement of sharing space with HTML in the source files. This language has some important strengths that make it the perfect candidate for use via the web:

PHP is an excellent scripting language for those who already have some programming background, and as an Open Source product, there are ample resources online to support users.

PHP Overview

PHP can easily be integrated with HTML, as such, PHP scripts can have entire blocks of HTML intertwined throughout the code. To start a PHP script (named with the .php extension) a PHP tag <?php will be used to start a section of code, and an end tag ?> will cause the web server to transition back to just returning the HTML directly. Note the missing portions of the tags, this is normal.

<p>Regular HTML</p>
<?php
  echo "<p>This is my first PHP code!</p>";
?>
<p>Back to Regular HTML</p>
Regular HTML

This is my first PHP code!

Back to Regular HTML
PHP Statements are separated by a semicolon ; and variables begin with a dollar sign $. Strings are handled in two different ways, 'single quotes' are used for literal strings, where "double quotes" are interpolated, meaning that variables within these strings will be replaced with their values.
<?php
  $example = 'cool, eh?';
  echo 'This is $example';
  echo "This is $example";
?>


This is $example
This is cool, eh?

Variable type is determined by content, variables are not declared prior to use! and variable names are case sensitive.
<?php
  $new_boolean = true;
  $new_int = 42;
  $new_force_double = (double) 42;
  $new_float = 3.14159;
  $new_string = "Automatically typed languages";
  $my_type = gettype($new_force_double);

  echo 'The type of $new_force_double ';
  echo "is $my_type";
?>








The type of $new_force_double
is double

We also have a nice way of combining strings via concatenation
$long_string = "line 1" . "line 2" . 'line 4';
$long_string = $long_string . $new_string;
Arrays are automatically declared upon use as well,
$new_array[0] = "Zero";
$new_array[1] = "One";
$new_array2 = array(0 => "Zero", 1 => "One", 2 => "Two");
$new_array3 = array('yes' => array('yes' => 4, 'no' => 3),
                   'no'  => array('yes' => 2, 'no' => 1));
We can also echo out a specific value of an array, which is slightly different then echoing out variables as seen earlier.

echo "This is how we output array elements - {$new_array['yes']}";

PHP Programming Constructs

As experienced programmers, it is often effective to present the varying constructs, if-statements, while-loops, etc., for review and learn via examples and practice.

for ($i = 0; $i < 5; $i++) {
  echo "$i ";
}
echo "<br>";

0 1 2 3 4

      
foreach ($new_array as $var => $value) {
  echo "$var -> $value <br>";
}

0 -> Zero
1 -> One
while ($new_int < 45) {
  $new_int++;
  echo "$new_int ";
}
echo "<br>";


43 44 45

      
do {
  $new_int++;
  echo "$new_int ";
} while ($new_int < 50);
echo "<br>";


46 47 48 49 50

      
if ($new_int == 42) {
  echo "new_int = $new_int and it is 42!";
} elseif ($new_int == 43) {
  echo "Why does new_int = 43?";
} else {
  echo "why does new_int not equal 42!";
}

new_int = 42 and it is 42!




      
switch ($new_int) {
  case 42:
    echo "still equals 42!";
    break;
  default:
    echo "why does it not equal 42!";
}


still equals 42!



      
If you wish to see if a variable has been created you can use the PHP function isset() to check to see if that variable is currently available.

Interacting with web pages

One of the greatest features of PHP is how well it work with the web. HTML code can surround PHP code and be handled natively, or as with all CGI scripts, HTML can be printed to stdout for display in the browser.

<?php
  echo "<b>PHP bold text<\b><br>"
?>
We are now in <em>HTML<\em>

PHP bold text
We are now in HTML

We are able to retrieve values from web forms via the PHP arrays $_GET, $_POST, and $_REQUEST. Note: $_REQUEST is the combination of both $_GET and $_POST.

<?php
  $user = $_POST['user'];
  $pswd = $_POST['password'];
  if ($pswd == 'happy') {
    echo "Welcome $user<br>";
  }
?>

Welcome Bob

Arrays

As a reminder, arrays are created on the fly by either defining the array or by creating an element within the array. In a more traditional number index array:

$array = array('thing0','thing1');
$array[2] = 'thing2';
We also have associative arrays, similiar to python dictionaries:
$prices = array('Tires' => 100, 'Oil' => 10);
$prices['Spark Plugs'] = 200;
PHP provides many different built-in sorting functions
sort($array);
ksort($prices);
asort($prices);
// Sort Array
// Sort associative array by key
// Sort associative array by value

PHP and Files

Working with files in PHP is painless, with methods that should feel familiar when compared to other languages you have worked with, example:

<?php
  $fileName = '';
  if (isset($_GET['filename'])) {
    $fileName = $_GET['filename'];
    $fp = fopen($fileName, 'r');   //open the file for reading
    if (!$fp) {                    //check that file opened ok
      echo "<p>ERROR! Could not open file $fileName for reading.</p>";
    } else {
      $line = fgets($fp);          // read a line
      while( !feof($fp) ) {
        $content = $content . $line . '<br>';
        $line = fgets($fp);
      }
    }
    fclose($fp);                   //close the file
  }
?>
PHP allows for the following modes when opening a file:

ModeDescription
r Read only, start at beginning of file.
r+Read/Write, start at beginning of file.
w Write only, opens and clears contents of file, or creates one if it does not exist
w+Read/Write, opens and clears contents of file, or creates one if it does not exist
a Write only, opens and writes to end of file, or creates one if it does not exist
a+Read/Write, preserves file contents by writing to end of file.
x Write only, Creates new file, returns false and error if file already exists
x+Read/Write, Creates new file, returns false and error if file already exists

Permissions

All of your work in this class will be stored on the midshipmen server midn.cs.usna.edu. If you work on your local machine, you need to copy the files to the midn.cs.usna.edu. Your local machine does not have a webserver with a PHP interpreter, so you will not be able to test your PHP scripts on your local machine. On the midn.cs.usna.edu server, your personal webpages are stored in the public_html directory within your home folder, and are visible online via http://midn.cs.usna.edu/~mXXXXXX The webserver runs as a separate user so you need to make sure that the files you create are viewable by this user. You might need to run the following in the directories with your code:

chmod 644 *.php *.html

Demo

In your public_html/IT350 folder make a new folder PHPIntro. Download the following files in your new PHPIntro folder and rename them if needed to have form.html, processPersonInfo.php and readPersonsInfo.php.

Now, from your browser, go to http://midn.cs.usna.edu/~mXXXXXX/IT350/PHPIntro/form.html. Fill in the information and submit the form. Did you receive the confirmation message? Does the confirmation message say that information was saved? If not, you might need to change permissions on the PHPIntro folder to allow the www-data user to write files in your folder.
In your browser, go to http://midn.cs.usna.edu/~mXXXXXX/IT350/PHPIntro/readPersonsInfo.php. Do you see the information previously enterered in the form?

Resources

The PHP website http://www.php.net provides an excellent source of documentation. Additionally, w3schools has ample information and examples for your review. The material in this class will provide the basic syntax behind PHP commands and data structures but more advanced uses may require outside research and investigation.

Debugging

You are expected to debug your code constantly, the best way to do that with PHP is to review the error log from the Apache web server. To review the logs:

  1. Log onto the web server (midn.cs.usna.edu) via ssh

    ssh midn.cs.usna.edu
  2. Tail (a command that allows you to see the last few lines of a file, or continuously watch the file for new additions with the -f flag) the error log via:

    tail -f /var/log/apache2/error.log
    It may be useful, to just focus on your own errors, and that can be done by piping the results of tail through grep to search for your mAlpha

    tail -f /var/log/apache2/error.log | grep mAlpha
  3. If any of the errors are confusing, take a look at the error guide located within the resources page of this class, or online. As with any language, it is recommended that you work on the first error that appeared, then try running your code again as errros may be linked to each other.
  4. Additionally, you can call your web page via the command line to see exactly what was returned, curl is an excellent utility for this, and the -v (verbose option) will show you the back-and-forth traffic with the web server.

    curl -v http://midn.cs.usna.edu/~mAlpha/IT350/test.php
  5. In Chrome, you can press ctrl-shift-j to toggle the debugger, this is useful as you can see exactly what was received by the browser.
Please note: When something is not working (internal server error), check the error log! You should be able to debug on your own, the instructor and/or the submission system can not be your primary method of finding errors in your code.

Practice Problems

  1. Create a simple helloworld.php program that prints out hello world via PHP
  2. Create a PHP script called form1.php that prints out a basic username / password form if either no input was received or if the password was wrong.
  3. Write a program that creates a simple web page by building a single string variable and filling it with the entire web page
  4. Write the PHP script ex1.php that will, given the URL provided below, generate HTML that looks like the screenshot http://midn.academy.usna.edu/~mXXXXX/IT350/CGIIntro/ex1.php?maxNumber=5
    cookies table