GEOG 863
GIS Mashups for Geospatial Professionals

PHP

PrintPrint

PHP is a recursive acronym – an abbreviation referring to itself – that stands for PHP Hypertext Preprocessor. It is a free and open-source web scripting language that, like JavaScript, is intermixed with HTML in a web page to generate content on the fly. Unlike JavaScript, PHP code must be executed by a web server as opposed to by the machine viewing the page. This is why PHP is often referred to as a server-side language, while JavaScript is referred to as a client-side language. The PHP website and the PHP Tutorial from the w3schools website are good resources for tutorials and language documentation for PHP.

A basic PHP file looks something like this:

<html>
    <head>
        <title>PHP example</title>
    </head>
    <body>
        <?php
            echo “Hello world”;
        ?>
    </body>
</html>
A basic PHP page in a web browser

Important items to note in looking at this example are:

  • PHP code is embedded within the HTML code.
  • PHP code is enclosed within the <?php and ?> tags.
  • The echo keyword is used to output a string. (Print may also be used in place of echo.)
  • All PHP statements must end with a semicolon. (Unlike JavaScript, in which the ending semicolon is optional.)
  • The document must be saved with a .php extension. This ensures that the server interprets and executes the PHP code in the file before sending the page to the client.

Note that either of the following alternatives can be used to produce the same result:

<html>
    <head>
        <title>PHP example</title>
    </head>
    <body>
        <?php
            echo “<strong>Hello world</strong>”;
        ?>
    </body>
</html>

<html>
    <head>
        <title>PHP example</title>
    </head>
    <body>
        <strong>
        <?php
            echo “Hello world”;
        ?>
        </strong>
    </body>
</html>

Comments in PHP

As with other programming languages, PHP programmers can add comments to their code to make it easier to follow or to "comment out" code that isn't working. The short example below shows how to add a single-line comment and a comment block.

  <html>
    <body>
      <?php
        // This is a comment

        /*
        This is
        a comment
        block
        */ 
      ?>
    </body>
  </html>

Variables in PHP

As in JavaScript, variables in PHP are untyped - meaning a developer need not specify a data type when beginning to use a variable. Unlike JavaScript, variables cannot be declared using a keyword like var. They are simply created using a name beginning with the $ character and referenced as in the example below:

<html>
  <head>
    <title>PHP example</title>
  </head>
  <body>
    <?php
      $msg = "Hello World";
      echo $msg;
    ?>
  </body>
</html>

The first character after the $ must be either a letter or an underscore (not a number).

PHP string concatenation

Whereas JavaScript uses the + operator to concatenate strings, PHP uses the . (period). See the example below:

<html>
  <head>
    <title>PHP example</title>
  </head>
  <body>
    <strong>
    <?php
      $last = ‘Mouse’;
      $first = ‘Mickey’;
      echo $first . $last;
    ?>
    </strong>
  </body>
</html>

PHP operators

All of the following PHP operators work the same as they do in JavaScript (notes added in parentheses for those that may not be obvious to you):

Arithmetic

+, -, *, /, ++ (increment by 1), -- (decrement by 1)

Comparison == (equals), != (not equals), >, <, >=, <=
Logical && (and), || (or), ! (not)

One area of difference in operators between the two languages is the concatenating assignment operator, which is often used to append additional text onto an existing string variable. For example, given a JS variable called x containing the string "Hello", additional text can be appended to x using the statement:
x += " World";

This syntax is often used in place of:
x = x + " World";

As you might guess, the PHP equivalent of the "+=" operator is ".=":
$x .= " World";

Conditional statements in PHP

The basic syntax of an if construct is the same as in JavaScript. The if condition must be placed in parentheses and all statements to be executed under the condition must be enclosed within braces. The only difference is that the "else if" construct is one word instead of two words:

if ($temp < 32) {
   echo “It’s freezing!”;
}
elseif ($temp > 90) {
   echo “It’s too hot!”;
}
else {
   echo “It’s comfortable.”;
}

PHP arrays

An array can be created in PHP using the following syntax:

$states = array("PA", "NY", "NJ", "DE");

Obtaining an individual array element is done by specifying the position of the element in brackets:

echo $states[0];

Loops in PHP

PHP offers two main types of loops (while and for) whose syntax and behavior is the same as in JavaScript. while is used to execute a block of code as long as some condition is met:

$i=1;
while($i<=5) {
  echo "The number is " . $i . "<br />";
  $i++;
}

for is used to execute a block of code a certain number of times:

for ($i=1; $i<=5; $i++) {
  echo “The number is “ .$i . “<br />”;
}

PHP's date() function

Of the many functions built into PHP, one of the more useful is date(), which is used to display both dates and times in various formats. The key to using the date() function is supplying a string argument that specifies the desired format. The following examples demonstrate its use:

Code Example Result
echo "Today is " .date("l"); Today is Monday
echo "The date is " .date("n/j/Y"); The date is 11/3/2008
echo "The current time is " .date("g:i:s a"); The current time is 4:04:25 pm

A complete list of formatting characters can be found at w3schools.

The date() function can also be used to format dates other than the current date. This is done by supplying a timestamp for the function's optional second parameter. A timestamp is the number of seconds since midnight, January 1, 1970. Assuming you don't know that value off the top of your head, you can calculate it using the mktime() function. The syntax of this function is: mktime(hour, minute, second, month, day, year). The following example demonstrates using the date() and mktime() functions together:

echo “July 4th, 2020 is a “ . date(“l”, mktime(0,0,0,7,4,2020));

String functions in PHP

Like other programming languages, PHP provides a number of functions that are used to manipulate strings. Some of the more useful of these include:

  • strlen() — returns the length of a string
  • strpos() — returns the position of one string inside another
  • strtolower() — converts a string to lower-case
  • strtoupper() — converts a string to upper-case
  • substr() — returns part of a string

Again, a more complete listing of PHP string functions can be found at w3schools.

PHP practice exercises

To help you gain a bit of comfort with PHP before we dive into its use in retrieving data from a database, please complete the following practice exercises. For each of the exercises, be sure to save your code with a .php extension and upload it to the special php folder in your personal web space to test it.

Note

While the www.personal.psu.edu server is configured to handle PHP scripts, it's not able to connect to the MySQL databases that have been set up for us. For that purpose, we'll use the phpdb.aset.psu.edu server instead. Although these practice exercises don't involve a database, to avoid confusion I'm going to recommend you use the phpdb server to execute all of your PHP scripts. This server is configured such that you can omit your access account ID from the URL. For example, I uploaded a script called date_function.php to my phpjed124 folder. I can execute that script and view its output using the URL https://phpdb.aset.psu.edu/phpjed124/date_function.php. You can follow the same pattern to execute your scripts.

  1. Create three variables (x, y, and z). Assign a value of 9 to x, a value of 7 to y and then make z equal to the sum of those two variables. Display the contents of the z variable on the screen using an echo statement.
    Solution to Practice Exercise 1
  2. Use the date() function to display your birthday in the following format:
    Friday, December 5, 2008
    Solution to Practice Exercise 2

In this part of the lesson, you read about PHP and got some practice with it. In the next part, you'll read a brief bit on the topic of setting up HTML forms to accept input from the user and accessing that input within your PHP scripts.