Web Programming/PHP

From Wikibooks, open books for an open world
Jump to navigation Jump to search

PHP[edit]

Resources:

PHP (stands for PHP Hypertext Preprocessor) is a programming language for processing web requests. When you use a browser to request or fetch a web page you are sending a request to the server. The web server know how to use the URL to find the file and send it back to your browser. PHP allows us to create programs on the web server and when the programs are requested the server send the output from the programs as the response. For this to work, the web server must know how to handle PHP files. Most web servers have the PHP module installed and when they see a request for a PHP file they will forward the request to the PHP module. The PHP module will parse the request parameters and invoke the requested PHP code.

This is a powerful idea. With PHP you can create programs on a web server that can dynamically create web pages using data sources from files to databases to other web services. Even though it is a simple request-response model on top of the web client-server model, we can be create powerful web applications by breaking down complicated interactions to a series of request-response cycles.

PHP is a scripting language. We create our programs as text files, which are also the executables. When a program is executed the PHP interpreter reads the source/executable file and execute one line of code at a time. Your PHP code can be tested on the server by using the interpreter as follows:

$php my_php_code.php

PHP Basic Syntax[edit]

In a PHP file you can intermix PHP code and static content. When the file is executed only the PHP code gets executed. The output from the code replaces the code part forming the output of the program with the static content intact. This design makes it easy to generate web pages using a template and injecting dynamic content into parts of the page.

A PHP code block is defined using a tag as shown in the example:

<!DOCTYPE html>
<html>
<body>

<h1>My hello world page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Please check out the following tutorials on w3schools.com to learn basic PHP syntax:

Examples[edit]

<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <?php
      $todos = array("Buy milk", "Buy eggs", "Read a book");
      $todo_count = 3;
      for ($i=0; $i<$todo_count; $i++){
        echo "<li>".$todos[$i]."</li>\n";
      }
    ?>
  </ul>
</body>
</html>

The HTML generate by the previous PHP script is as follows:

<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <li>Buy milk</li>
<li>Buy eggs</li>
<li>Read a book</li>
  </ul>
</body>
</html>

The indentation is not what we expected and we could print the space or the tab characters from the PHP script but it would be very tedious. Instead we can use expression blocks to inject dynamic contents to the static ones as shown in the following example.

<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <?php
      $todos = array("Buy milk", "Buy eggs", "Read a book");
      $todo_count = 3;
      for ($i=0; $i<$todo_count; $i++){?>
    <li><?=$todos[$i]?></i>
    <?php  }
    ?>
  </ul>
</body>
</html>
<html>
  <head>
    <title>My TODO list</title>
  </head>
<body>
  <ul>
    <?php
      $todos = file("todolist.txt");
      $todo_count = count($todos);
      for ($i=0; $i<$todo_count; $i++){
        echo "<li>".$todos[$i]."</li>";
      }
    ?>
  </ul>
</body>
</html>

PHP String Functions[edit]

Functions are reusable blocks of code. PHP has a set of build-in string functions for manipulating strings. A partial list of string functions is as follows:

The explode function allows us to "unpack" a string into a array of substrings. The following code

<?php
  $items = explode(":", "item1:item2:item3");
  print_r($items);
?>

will output

 Array
(
    [0] => item1
    [1] => item2
    [2] => item3
)

You can name the substrings using the list notation. The following code

<?php
  list($a, $b) = explode(":", "item1:item2:item3");
  print "a=".$a."\n";
  print "b=".$b;
?>

will output

a=item1
b=item2

The implode function packs a array of strings into a single string.

PHP Array Functions[edit]

Python array allows us to refer to a collection of items using a single variable. The items can be of any datatype including array (how multi-dimensional arrays are created). The size of a Python array is not fixed. In fact there are functions that allow you to treat an array as a queue or a list. Some example array functions are as follows:

PHP Global Variables[edit]

PHP superglobal variables are a set of predefined variables that are always accessible to all PHP scripts on the server.

They are:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

The following script

<?php
  print_r($_SERVER);
?>

will output content similar to

Array ( 
[HTTP_HOST] => 198.209.99.99 
[HTTP_CONNECTION] => keep-alive 
[HTTP_CACHE_CONTROL] => max-age=0 
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 
[HTTP_USER_AGENT] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.122 Safari/537.36 
[HTTP_ACCEPT_ENCODING] => gzip,deflate,sdch 
[HTTP_ACCEPT_LANGUAGE] => en-US,en;
...

As you can see the server gets all kinds of information from the client through the HTTP request sent and makes the information available to the PHP scripts via the $_SERVER variable.

If we request the following script using the following URL: http://host/path/to/test.php?first_name=Curious&last_name=George the script will echo back the parameters sent via this request.

<?php
  print_r($_REQUEST);
?>

The actual output is

Array ( [first_name] => Curious [last_name] => George )

$_REQUEST is an associative array with strings as indices. You can refer to the elements in the array by their names, for example $_REQUEST["first_name"] will give you the value of "Curious". If you expect a parameter to be sent to your script via the query string you can attempt to get it through this $_REQUEST variable. The following script test whether the parameter is sent and echoes "first_name parameter is missing." if the parameter is not provided in the query string.

<?php
  $first_name = $_REQUEST["first_name"];
  if (isset($_REQUEST["first_name"])){
    print "first_name=".$first_name;
  }else{
    print "first_name parameter is missing.";
  }

PHP File Functions[edit]

PHP file functions allows us to access and manipulate the filesystem on the server on which our PHP scripts are executed. The basic file functions include reading content from a file or a directory and writing to a file. Some commonly used file functions are as follows:

The following PHP script reads a poem from a file and outputs it as a ordered list.

<ol>
<?php
  $lines = file("poem.txt");
  foreach ($lines as $line){
?>
    <li><?=$line?></li>
<?php
  }
?>
</ol>

The output will appear as follows in a browser window:

1. All that is gold does not glitter,
2. Not all those who wander are lost;
3. The old that is strong does not wither,
4. Deep roots are not reached by the frost.
5. From the ashes a fire shall be woken,
6. A light from the shadows shall spring;
7. Renewed shall be blade that was broken,
8. The crownless again shall be king.

Reading a directory is similar to reading a file except that the result is a list of files and directories of the directory we are reading. The glob function allows us to scan a directory to read items (file or directory) that matches a pattern. The following script reads names of text files that are in the "word" subdirectory, which is under the directory that contains the script.

<?php
  $file_names = glob("words/*.txt");
  print_r($file_names);
?>

As shown in the output below the array returned from the glob function contains relative paths to the files, which makes it easy to read the files (next example).

Array ( [0] => words/hits.txt [1] => words/words.txt )

The next script takes the paths to the files, reads the file contents, and echoes them back to the caller.

<?php
  $files = glob("words/*.txt");
  foreach ($files as $file){
    $content = file_get_contents($file);
?>
  <h1><?=basename($file)?></h1>
  <?=$content ?>
<?php
}
?>

A sample output of the script is as follows. The basename function returns the path's last component, which is the "bare" file name.

 <h1>hits.txt</h1>
 123
 <h1>words.txt</h1>
 prothalamion	noun	a song in celebration of a marriage
 atrabilious	adjective	given to or marked by melancholy; GLOOMY
 hyacinth	noun	a precious stone of the ancients sometimes held to be the  sapphire; a gem zircon or essonite

PHP Include Statement[edit]

PHP include statement copies the content of another file into the current file where the include statement appears. For example, the following statement will "include" the output of the navigation.php script (e.g. HTML code for a navigation bar) into its own output.

<?php include "navigation.php"; ?>