CPSC 343 Database Theory and Practice Fall 2017

PHP Quick Start

This document is intended to be a quick start to the PHP language, for someone who is already familiar (and comfortable) with C, C++, or Java and is interested in using PHP to create dynamic web pages. Refer to the PHP Web Quick Start for information on getting information about the web server environment, processing HTML forms, and working with sessions and cookies, the PHP MySQL Quick Start for information on interacting with MySQL from PHP, or the HTML/PHP Local Quick Start for local details such as where to actually put your PHP pages so you can try them out.

Many details are omitted or simplified in these Quick Starts (e.g. not all syntax variations are presented). For more detailed and extensive information, check out one of the links below:


Contents


A Basic PHP-Enabled Page

PHP commands are embedded in regular HTML files - the files do not need to be executable. The following demonstrates a very basic PHP-enabled web page: (helloworld.php)

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php print "<p>Hello World</p>"; ?>
 </body>
</html>

PHP commands are embedded in PHP tags, starting with <?php and ending with ?>. Note that this format is slightly different than regular HTML tags.

When the webserver receives a request for a PHP-enabled web page, the HTML that is sent back to the client is produced by running the PHP page through the PHP processor. The PHP processor begins in HTML mode - when in HTML mode, the processor merely echoes back everything it encounters (so you can think of the raw HTML going directly back to the client). A <?php tag causes the PHP processor to enter PHP mode - in PHP mode, the processor treats what it sees as PHP and executes the commands. The processor exits PHP mode and returns to HTML mode when the ?> tag is reached.

Since HTML is being sent back to the client, it is necessary to make sure that any output generated by PHP commands is HTML-formatted (hence the <p>...</p> tag in the example). Also, remember that the PHP commands are executed by the server, not the client.


PHP Language Syntax

PHP's language syntax is similar in many ways to perl, which is, in turn, similar to C, C++, Java, and many other languages. You may be able to guess at the syntax and have your script work, particularly if you are familiar with perl. The basics listed below should be enough to get you started; the "about" links for each topic will take you to the appropriate section of the PHP Manual for more information.

Some basics:


PHP and HTML

(about escaping from HTML)

When an HTML file containing PHP code is processed, the HTML is output exactly as it is in the file and each chunk of PHP code is executed. You can imagine the PHP processor getting the whole file - it outputs exactly what it sees if the content isn't inside <?php...?> tags, and executes the code if it is inside <?php...?> tags.

A simple web page which displays the current date and time (as of when the page was last loaded): (datetime.php)

<html>
<head>
<title>Date and Time Demo</title>
</head>
<body>
<h2>Current Time</h2>
<p>It is currently <?php print date("l F j, Y g:i:s a"); ?>.</p>
</body>
</html>

When the client (a web browser) sends a request for this page, the PHP processor on the web server outputs the HTML as is until it gets to the <?php print date("l F j, Y g:i:s a"); ?> section - where it executes the date function and outputs the result - and then continues outputting the remaining HTML as is. Note that it is the server which executes the PHP - if you View Source in your browser, you'll see only the resulting HTML and not the original source with the PHP.

This page can be expanded (in a similar manner) to also display the time of sunrise and sunset for that day: (datetime2.php)

<html>
<head>
<title>Date and Time Demo</title>
</head>
<body>
<?php
define("LATITUDE",42.87);
define("LONGITUDE",-76.98);
define("TIME_FORMAT","g:i:s a");
$now = time();                       // right now
?>
<h2>Current Time</h2>
<p>It is currently <?php print date("l F j, Y g:i:s a",$now); ?>.</p>
<h2>Almanac [Geneva, NY]</h2>
<ul>
<li> Sunrise time: 
<?php 
$sunrise = date_sunrise($now,SUNFUNCS_RET_TIMESTAMP,LATITUDE,LONGITUDE);
print date(TIME_FORMAT,$sunrise);
 ?>
<li> Sunset time:
<?php 
$sunset = date_sunset($now,SUNFUNCS_RET_TIMESTAMP,LATITUDE,LONGITUDE);
print date(TIME_FORMAT,$sunset);
 ?>
</ul>
</body>
</html>

This example makes use of constants (via define), variables ($sunrise and $sunset), and several more built-in functions (time, date_sunrise, and date_sunset) but it still works in the same way as the first example - snippets of PHP are embedded in the HTML to produce chunks of dynamically-generated output. Note that the scope of the constants and variables extends past the <?php...?> tags where the variable is first used - LATITUDE, LONGITUDE, TIME_FORMAT, and $now are all used in multiple places.

You can also get fancier, and use the control structures that PHP provides to control the output. For example: (datetime-week.php)

<html>
<head>
<title>Date and Time Demo</title>
</head>
<body>
<?php
define("LATITUDE",42.87);
define("LONGITUDE",-76.98);
define("TIME_FORMAT","g:i:s a");
$now = time();                        // right now
?>
<h2>Current Time</h2>
<p>It is currently <?php print date("l F j, Y g:i:s a",$now); ?>.</p>
<h2>Almanac [Geneva, NY]</h2>
<p>Sunrise and sunset times for the next week.</p>
<table border=0 cellpadding=3>
<tr><th>Date</th><th>Sunrise</th><th>Sunset</th></tr>
<?php
for ( $day = 0 ; $day < 7 ; $day++ ) {        // count for the next week
  $date = strtotime("+".$day." days",$now);
  $sunrise = date_sunrise($date,SUNFUNCS_RET_TIMESTAMP,LATITUDE,LONGITUDE);
  $sunset= date_sunset($date,SUNFUNCS_RET_TIMESTAMP,LATITUDE,LONGITUDE);
  print "<tr><td>".date("l F j",$date)."</td><td>".
        date(TIME_FORMAT,$sunrise)."</td><td>".date(TIME_FORMAT,$sunset).
        "</td></tr>\n";    // \n at end puts a line break in the
	                         // generated HTML, making it more readable
}
?>
</table>
</body>
</html>

This displays a table of the sunrise/sunset times for the next week. The loop causes the print that produces a row of the table to execute multiple times. Also note that the print includes the HTML tags necessary for one row of the table - remember that the goal of the PHP along with the static HTML is to produce an HTML page.

It can be annoying to have to include HTML tags in a print statement, particularly if those tags include double quotes (because the double quotes must then be escaped by writing \" instead of just ") or if there is a lot of HTML to output. It is possible to interleave the PHP and HTML even more than was done in the last example: (datetime-week2.php)

<html>
<head>
<title>Date and Time Demo</title>
</head>
<body>
<?php
define("LATITUDE",42.87);
define("LONGITUDE",-76.98);
define("TIME_FORMAT","g:i:s a");
$now = time();                        // right now
?>
<h2>Current Time</h2>
<p>It is currently <?php print date("l F j, Y g:i:s a",$now); ?>.</p>
<h2>Almanac [Geneva, NY]</h2>
<p>Sunrise and sunset times for the next week.</p>
<table border=0 cellpadding=3>
<tr><th>Date</th><th>Sunrise</th><th>Sunset</th></tr>
<?php
for ( $day = 0 ; $day < 7 ; $day++ ) {        // count for the next week
  $date = strtotime("+".$day." days",$now);
  $sunrise = date_sunrise($date,SUNFUNCS_RET_TIMESTAMP,LATITUDE,LONGITUDE);
  $sunset= date_sunset($date,SUNFUNCS_RET_TIMESTAMP,LATITUDE,LONGITUDE);
?>
<tr><td><?php print date("l F j",$date); ?></td>
    <td><?php print date(TIME_FORMAT,$sunrise); ?></td>
    <td><?php print date(TIME_FORMAT,$sunset); ?></td></tr>
<?php
}                                               // end of loop
?>
</table>
</body>
</html>

This does exactly the same thing as the earlier example - it prints out the current date and time, plus the sunrise and sunset information for the next week. To understand how it works, keep in mind how the PHP processor works - it outputs HTML as is while executing the PHP code. In the case of the loop, the PHP processor executes the initialization ($day = 0), the test condition ($day < 7), and proceeds into the body because the condition is true. In the body, it executes the first three lines, then drops back to HTML mode when the ?> tag is reached. <tr><td> is output as is, then it goes back to PHP mode to execute date, and back to HTML mode to output </td>. This continues until the close } for the loop is encountered, in which case (in PHP mode), execution continues with the loop update ($day++), the test condition, and so forth.

Use good judgement when deciding whether to include HTML tags in the print statement or to interleave PHP and HTML as in the last example - things can quickly get unreadable if you do not make an effort to structure your code as carefully as possible using sensible interleaving, indentation, and comments.


Includes

(about include)

Much like #include in C++ programs, the PHP include statement allows the contents of one file to essentially be pasted into another file. This can be convenient for common definitions which are used in many different files - each file can include the common file, and changes made to just the common file are automatically incorporated everywhere that includes it.

When processing an include, the processor goes into HTML mode at the start of the included file and returns to HTML mode at the end - so the included file should enclose any PHP in proper tags.

This example uses include to include hit-counting code on two separate pages. (The hit-counting code itself uses session variables - see Sessions, Cookies, and Hidden Form Elements in the PHP Web Quick Start.)

The first page: (include1.php)

<?php
  session_start();
 ?>

<html>
<head>
<title>Include Example, Page 1</title>
</head>
<body>
<p>This is an exciting page.</p>
<?php include "hitcounter.php"; ?>
</body>
</html>

The second page: (include2.php)

<?php
  session_start();
 ?>

<html>
<head>
<title>Include Example, Page 2</title>
</head>
<body>
<p>This page is even more thrilling than the first.</p>
<?php include "hitcounter.php"; ?>
</body>
</html>

The common hit-counting code: (hitcounter.php)

<?php
  // use unique name for each file, by basing the variable name on the filename
  $count_varname = $_SERVER["PHP_SELF"]."_count";  
  if ( !isset($_SESSION[$count_varname]) ) {
    $_SESSION[$count_varname] = 1;
  } else {
    $_SESSION[$count_varname]++;
  }
 ?>

<hr>
<p>You have loaded this page 
<?php print $_SESSION[$count_varname]; ?> time(s).</p>

Note that the included file (hitcounter.php) doesn't contain all the <html>, <title>, etc tags of a complete HTML document - its contents are essentially pasted into the including file, so it only contains exactly what needs to be pasted in.


Debugging

If you get output but it isn't what you expected (perhaps the formatting is wrong, or the content isn't correct), you can View Source in your browser to see the HTML that was returned by the server. This can often be enough to figure out what the problem is.

PHP syntax errors are harder to handle - because the PHP is executed by the web server, error messages are logged to the web server log by default. Check the Local Quick Start for information on how to access the error log.

You can also use the show_source() function to get a syntax-highlighted copy of the source code of a PHP file - odd highlighting can point you towards some errors. show_source() takes the filename whose source is to be displayed as a parameter: (about show_source)

<?php
   show_source("page.php");
 ?>

Valid HTML 4.01!