Pages

Banner 468

Sunday 10 April 2011
0 comments
 

Server-Side Languages 2 - Basic PHP


In my last post, we looked at how to use XAMPP to set up an Apache web-server that includes MySql and PHP.

This post will focus on the PHP server-side language itself and how we can use it to generate dynamic web pages.

What is PHP?


PHP is a free, platform independent scripting language originally developed way back in 1995 specifically for creating dynamic web pages. PHP originally stood for “Personal Home Page”, however it is now widely accepted that PHP is a recursive acronym standing for “PHP: Hypertext Preprocessor”. Whatever the meaning, PHP has grown into one of the most popular scripting languages in use today.

As with any programming language, the best way to learn/explain how it works is through practical examples. During this post I will introduce basic PHP syntax and how to use variables, arrays and loops to create (step-by-step) a simple page that dynamically displays a list of usernames and passwords.

Step 1 – “Hello World”


The following snippet shows a simple HTML page with some embedded PHP code between the '<?php' and '?>' tags.  Any text between these tags will be interpreted by PHP on the web server before sending the page to the client (web browser).  In this case,  we are using the 'print' PHP construct to place "Hello World!" between the <h1> tags.  Furthermore we are using a double forward slash (//) to add a single line comment to the script.

<html>
      </head></head>
      <body>
         <h1>
            <?php
               //Display "Hello World!" between h1 tags
               print "Hello World!";
            ?>
         <h1>
      </body>
   </html>

We could also use 'echo' instead of 'print' to produce the same effect. So what's the difference? Basically both 'echo' and 'print' are PHP constructs that output text to the screen but the difference lies in how they are structured and not what they do. Basically the 'print' construct returns a value, just like a function, while 'echo' does not. What this means is that when looping through an extended amount of iterations, 'echo' performs faster than 'print'.

Step 2 - Variables

PHP is a loosly-typed language meaning that we do not need to specify a datatype when declaring variables.  In the following code snippet, I will create two variables to store values for a username and a password and use the echo construct to display these values to the user:

<html>
   <head></head>
   <body>
      <?php
         /*
           Declare variables.  
           All variables in PHP start with a '$' sign
         */
         $Uname = 'guest';
         $Pword = 'guest123';            
            
         echo "Username: ".$Uname."<br>";
         echo "Password: ".$Pword;

      ?>
   </body>
</html>

Pretty straight forward so far. One thing of note however is how the value of a variable is being concatenated to the rest of the string. In PHP the concatenation operator is the '.' rather than the more commonly used '+'.

Before going onto arrays I would like to demonstrate how to replicate the above example using constants rather than variables. Constants are 'special' variables whose values cannot change, or remain constant (hence the name). Here's how the above example would look like when using constants:

<html>
   <head></head>
   <body>
      <?php
         /*
            Define constants.  
            The value of a constant cannot be changed
         */
         define ('Uname', 'guest');
         define ('Pword', 'guest123');        
         
         echo "Username: ".Uname."<br>";
         echo "Password: ".Pword;
      ?>
   </body>
</html>

Constants are defined using the 'define()' function, passing the name of the constant and its value as parameters. Unlike variables, names of constants must start with a letter or an underscore and are - by default - case sensitive (like the rest of the language for that matter).

Step 3 - Arrays


In PHP we can use three kinds of arrays:

  • Numeric Arrays
  • Associative Arrays
  • Multidimensional Arrays

I have already discussed numeric arrays in detail in previous posts so I will focus on Associative Arrays instead (We'll tackle multidimensional arrays in my next post).

An associative array is basically a collection of key-value pairs whereby we can retrieve a specific value based on a string key rather than a numerical index. Associative arrays are used extensively in PHP: $_REQUEST, $_SESSION and $_COOKIE are all examples of pre-defined associative array variables. $_COOKIE for instance is an associative array that stores variables passed to the script through HTTP cookies. We will see these (and more) of these pre-defined variables in action in the next post, but for now we will see how we can define and use our own associative arrays.

As mentioned at the beginning of this post, I want to create a script that displays a table of usernames and passwords to the user. In the next code listing, I will define an associative array to store my username and password 'pairs':

<html>
   <head></head>
   <body>
      <?php
         // Define the associative array
         $users = array("admin"=>"admin123",
                        "user1"=>"letmein",
                        "guest"=>"guest100,"
                        "Wimpy"=>"hamburgers");
      ?>
      <h3>User List</h3>
      <table border="1">
         <tr>
            <th>Username</th><th>Password</th>
         </tr>
         <tr>
            <?php 
               echo "<td>admin</td>";
               echo "<td>".$users['admin']."</td>";
            ?>
         </tr>
         <tr>
            <?php 
               echo "<td>user1</td>";
               echo "<td>".$users['user1']."</td>";
            ?>
         </tr>
         <tr>
            <?php 
               echo "<td>guest</td>";
               echo "<td>".$users['guest']."</td>";
            ?>
         </tr>
         <tr>
            <?php 
               echo "<td>Wimpy</td>";
               echo "<td>".$users['Wimpy']."</td>";
            ?>
         </tr>
       </table>
   </body>
</html>

Best practices apart, the above example demonstrates how to define an associative array (line6) where the key-value pairs are the usernames and passwords respectively. Simple echo statements are used to display the users as an HTML table. This is obviously not the best way to do this. One of the advantages of arrays is that they allow us to iterate through their values, which brings us to the final topic of this post:

Step 4 - Looping Through Associative Arrays


As we have seen, associative arrays are based on string values (keys) rather than numeric indices which means that we cannot use a counter in a for loop to iterate through the array. We can however use the foreach loop or the each() and list() constructs instead.

Method 1 - The Foreach Loop

<?php
   // Define the associative array
   $users = array("admin"=>"admin123",
                  "user1"=>"letmein",
                  "guest"=>"guest100",
                  "Wimpy"=>"hamburgers");
?>

<h3>Method 1 - Simple Foreach</h3>
<table border="1">
   <tr><th>Username</th><th>Password</th></tr>
   <?php  
      foreach($users as $username => $password)   
         echo "<tr><td>".$username."</td>";
         echo "<td>".$password."</td></tr>";
   ?>

</table>
In this method, we use a simple foreach loop to iterate through each username and password pair. During each iteration, the values of the current element in the array copied into the '$username' and '$password' variables respectively which are then used in the echo statements further down.
Method 2 - Using the 'each()' construct
We can also use the each() construct within a while loop to iterate through the array. Each() will return the current key and value pair as a four element array which allows us to get the value either through the key or through a numeric index. Using our $users array as an example, the first time 'each($users)' is called, the returned array, say $user, would look like this:
$user
(
[0] = 'admin'
[key] = 'admin'
[1] = 'admin123'
[value] = 'admin123'
)

Here's what the code looks like when using 'each()':

<?php
<h3>Method 2 - Using the each() construct </h3>

<table border="1">
   <tr><th>Username/th><th>Password</th></tr>
   <?php
      while($user = each($users))
      {
         echo "<tr><td>".$user['key']."</td>";
         echo "<td>".$user['value']."</td></tr>";
      }
   ?>

</table>
Since the 'each()' construct sets the array cursor to the next element in the array (or beyond), you must use the 'reset()' function to use the array with 'each()' again.
There is however a more common way of using 'each()' which also easier to understand:

Method 3 - Using 'each()' and 'list()'

while (list($uName, $pass) = each($users))

The above statement executes the 'each()' function to get the current key-value pair of the $users array and makes the next element current. The 'list()' function takes the [0] and [1] elements of the array returned by 'each()' and places the values into variables named '$uName' and $pass. We can then 'echo' the values of these variables as usual.

Conclusion

During this rather lengthy post we have taken a look at some baisc PHP and how we can use this popular scripting language to generate some dynamic content on the server. Being an ASP.net developer myself, this was my first experience in working with PHP. I must admit that although PHP is easy to learn, the lax nature of the language allows for some really bad-practice coding. The real challenge in my opinion is not learning the PHP syntax itself, but rather learning how to use it well in a disciplined and ordered manner. Raw PHP reminds me of the old ASP days where the notion of separating code from markup was something we fantasized about. Full-blown ASP web applications were a nightmare to maintain due to the way code and markup was intertwined in true spaghetti fashion.
There are however patterns and frameworks that help mitigate this problem and I will definitely look into them in the near future.
In my next post, I will be building a simple login page and use PHP to 'authenticate' users and we will also look at how we can use and manage sessions and cookies.

Leave a Reply