CPSC 343 | Database Theory and Practice | Fall 2024 |
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:
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'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:
All statements end with semicolons. (about instruction separation)
C++-style single-line // and multiline /* */ comments are supported. (about comments)
The basic primitive types are boolean, integer, float (like double in C++/Java), and string. Boolean values are TRUE and FALSE. Unlike C++ and Java, types are not usually specified explicitly — PHP deduces them at runtime based on how the variable is used. (You should have the type of each variable you use in mind, though, to avoid using it inappropriately.) (about types — basics, about boolean, about integer, about float, about string)
Variables are indicated by a $ followed by the (case-sensitive) name of the variable e.g $x. Variable names must start with a letter or underscore, and may contain only letters, digits, and underscores. Variables do not need to be declared; they come into existence when first used. Variables used outside any function have global scope and variables used inside a function are limited to that function; however, unlike C, C++, and Java, global variables are not automatically available within a function. (about variables — basics, about variable scope)
Constants are defined with the define function:
<?php define("GREETING","hello world"); print GREETING; // outputs "hello world" ?>
By convention, names of constants are all caps. There is no $ before the name of the constant, either when it is declared or when it is used. The value of a constant may only be a boolean, integer, float, or string (no arrays). Constants may not be redefined or undefined once set and may be defined and accessed anywhere (the scoping rules for variables do not apply). (about constants)
The usual C++/Java arithmetic, comparison, and boolean operators are supported. (complete list)
String concatenation is done via . instead of +:
<?php $x = 5; print "the value is ".$x; ?>
if statements have nearly the same syntax as in C++/Java — the one difference is that elseif is one word instead of two. (about if, about else, about elseif)
while and for loops have the same syntax as in C++/Java. break and continue also work in the same way. (about while, about for, about break, about continue)
Functions are similar to C++/Java, but without explicitly-mentioned types and with the keyword function:
<?php function average ( $num1, $num2 ) { return ($num1+$num2)/2; } ?>
By default, function arguments are passed by value. Use an ampersand & in front of the parameter declaration in the function header if you want pass by reference.
Function calls take the same form as in C++/Java:
<?php $x = 10; $avg = average($x,20); ?>
(about functions, about function arguments, about return values)
PHP has many built-in functions, though the availability depends on what modules PHP has been configured with. (complete list)
Unlike C++/Java, arrays may be indexed by strings or integers (the index for a particular element is known as a key) and are not constrained to contain only elements of the same type. (This kind of array is known as an associative array.) Arrays are created with the array language construct:
<?php $arr1 = array( 10, 20, 30, 40 ); $arr2 = array("name" => "Alice", "age" => 20, "color" => "blue"); ?>
$arr1 contains the four elements 10, 20, 30, and 40 with keys 0, 1, 2, and 3, respectively. $arr2 contains three elements ("Alice", 20, "blue"), with keys "name", "age", and "color" respectively.
Like C++/Java, square brackets are used to index into the array:
<?php print $arr1[0]; // 10 print $arr1[3]; // 40 print $arr2["name"]; // "Alice" print $arr2["age"]; // 20 ?>
Some other array manipulations:
<?php $arr2["name"] = "Bob"; // changes the value associated with name $arr2["address"] = "123 Main St."; // adds new entry to $arr2 unset($arr1[2]); // removes 30 unset($arr2["color"]); // removes "blue" (and the key "color") if ( isset($arr2["color"]) ) { // isset returns true if the specified // variable has a value (in this case, it // returns false) print "yup!"; } print_r($arr1); // prints all the keys and values of $arr1 print count($arr2); // prints number of elements in the array ?>
Iterate through arrays with foreach:
<?php $arr = array("name" => "Alice", "age" => 20, "color" => "blue"); foreach ( $arr as $value ) { // loop through each element in the array print $value; } foreach ( $arr as $key => $value ) { // loop through each key and element // in the array print "key: $key / value: $value"; } ?>
In the first form, the variable following "as" ($value in the example) is assigned each value in the array ($arr in the example) in turn. In the second form, the variables following "as" ($key and $value in the example) are assigned each key and the corresponding value in turn. The body of the foreach is carried out once for each value or key/value assigned. (about foreach)
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.
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.
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 different — because the PHP is executed by the web server, error messages are logged on the server rather than the client. Check the Local Quick Start for information on how to access PHP error messages.
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"); ?>