Pages

Monday, 11 April 2011

Introduction to PHP

Introduction


This week's post will be about the PHP server side technology. It will include two tasks which I merged into one big post. 

Taks 1 is very short and consists in:
  • Verifying that PHP works on the web server.
  • Creating an associative array of user names and passwords and listing the entire array in a table.
  • Explaining the difference between the echo() and print() functions.

Task 2 adds up to the first task. Duties for task 2 include:
  • Using PHP to create a login screen that accepts a user and a password that are validated on the server side.
  • Adding a “remember me” option that uses a cookie so that the user does not have to log in again.
  • Replacing the cookie mechanism with PHP sessions.


Some notes about PHP


On the main PHP website, PHP is described as a general purpose scripting language with the goal of allowing web developers to create Dynamic web pages. PHP can be embeded in HTML and uses syntax similar to other common languages such as C and Java.

PHP is useful when developing large websites as it would take less time to develop in PHP than in any other language. This language is easy to learn and provides a great deal of inbuilt commands that are useful when creating a website.

PHP is a Loosely-Typed Language, meaning that a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.

Unlike in Strongly typed languages, in  PHP there is no need to declare the variable type. The variable type is chosen automatically when a variable is used.

Task 1


To test my web server, I connected my notebook to my home network and launched the apache server, through the XAMPP control Panel. Then I created a simple PHP webpage and saved it in the web server's path. Finally I tried to access it from another PC on the network and everything worked fine.

Creating an Assosiative Array


Well the first thing I did when I saw the first task, was to go to http://www.w3schools.com/ where I took a very short tutorial about PHP. I was not new to programming because I already have a little knowledge in Java and some .NET languages, but I had never written or seen any PHP script before. Since I am more used to program in strongly-typed languages, PHP seems a bit dangerous for me because there is a greater change to get confused when using variables. After reading the tutorial I tried to create my first script. I used the echo function to get a grasp of how PHP works.

In the array section of the tutorial there was an easy way to create an associative array and I used that method to create mine. An associative array is an array that allows the mapping of string keys to values, rather than the traditional zero-based index. In this type of array values can be used as keys that reference to other values. For the purpose of this task i created an array of Passwords using usernames as keys that map to the corresponding password. Notice how I used \$ instead of just $ to insert a dollar sign as part of the password.

$Passwords = array("Mark"=>"Galea", "Paul"=>"Borg", "Joe"=>"pa\$\$word");

This next part of the task is to display the array in a table on a web page. To list the usernames and password in a table, I used a loop that goes through all passwords and echoes each line in  <tr> and <td> tags that form the rows and cells of the display table. The function below starts by creating the previously described array, on Line 4. Line 5 and Line 6 show the use of the echo functions to create the initial tags of the HTML table.
The reset function on line 7 resets the array index of $Passwords, to the first element. The while function is used to loop through the elements in the password array. The each function returns the both the key and value of each element in the array while the list function assigns the key value to the $Key variable and the actual value to the $value variable. In this case, the $key is the username and the $value is the password. These values are echoed together with the appropriate HTML Tags to for a table. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

<?php
function showPSD()
{
$Passwords = array("Mark"=>"Galea", "Paul"=>"Borg", "Joe"=>"pa\$\$word");
echo "<div><br/><table border='1'><tbody >";
echo "<tr><th>Username</th><th>Password</th></tr>";
 reset ($Passwords);
while(list($key,$value)=each($Passwords))
    {
     echo "<tr ><td>" . $key . "</td>";
     echo "<td >" . $value . "</td></tr>";
     }
echo "</tbody></table></div>";
}
?>

The above table would look like this:

Difference between echo and Print functions


The echo functions and the print functions, both do the same thing which is inserting text into the webpage's HTML. Although they do the same thing, they work slightly differently.

Well the first difference is that echo can print more than one line at a time, separated by a comma, while the Print function can only print one line at a time. Echo is faster than print, although not noticeable at all by users. This is because echo is more similar to a command while print works more like a function which also returns a value. Since print returns a boolean value, it can be used in situation where the value true must be returned after inserting text in the html. Print could be used in a situation similar to this:

$something $myvar ? print("Success!") : false


Task 2


For task 2 I reused the array in task one to store the login details for the login screen. I decided to make a simple white, clean, centered login screen for this task since I was more concerned about the functionality of the page rather than it's looks.

Creating the Login Screen


The login screen consists of a header, and a table with two columns. The first two rows of the table contain the username and password, labels and input fields. Password uses password as input type, such that the content entered by the user is not visible on screen. The table is only used for alignment as is not actually visible. The screen also has a remember me check box and a Login button.


The user of the webpage must enter his user name and password and click on the login button. The login button submits the form and the values entered are validated. If the username and password are correct, the user is redirected to another page, else an error message is displayed. The code below shows the validation process.


1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

<?php
if(isset($_POST['btnLogin']))
{
  $username = $_POST['txtUserName'];
  $password = $_POST['txtPassword'];
  $Remember = isset($_POST['ckRemember'])? true:false;

      reset ($Passwords);
     while(list($key,$value)=each($Passwords))
       {
        if ($key == $username && $value==$password )
         {
         $date = getdate();
         setcookie('LastLogin', Date('d/m/Y').' '.$date[hours].':' .$date[minutes].':'.            $date[seconds],time()+3600);
          if ($Remember == true)
             {
              setcookie("User",$username,time()+3600);
              }
          else
             {
              setcookie("User","",time()-3600);
             }

          header('Location: coursework_2p2.php?Name=' . $username);
          }
       }
      echo "<script>alert('Invalid Login')</script>";
    }
?>

Line 2 of the above table, shows the isset() function that verifies if a variable or object exists. In this case it is being used to check if the submit button was clicked. Lines 4 and 5 show how the values entered in the input boxes can be captured. The $_Post["itemName"] gets the values of the posted items.  To capture the value of a Check Box, I had to use the isset() function, because the post value of the check boxes is only created if the check box is checked, and therefore an error would be generated if i tried to get the post value of a non-checked check box. Similarly to what I did in task 1, I used the while loop on line 9 to loop through all login details. The if statement on line 11 checks if the login details entered match any of those in the $passwords array. In case of a valid login, I used the header function to go to another page and passed the username as a string query. The browser is then redirected to another webpage showing a welcome screen with the user name. If no login matches those in the array, line 28 is executed showing an alert saying invalid login.


In case of a valid login the welcome label on the redirected page is retrieved using the $_GET['ItemName'] Method. I used the following code in my screen :

echo "<h1>Welcome ". $_GET['Name']."</h1>";

The resultant page looks like this, with Mark being the username entered in the previous screen. Please ignore that date and the log out button for now.

Remember Me Feature


Instead of the remember me button as suggested, I used a check box for the remember me feature. When the check box is checked, a cookie is saved in the browser as saves the username of the valid login. Line 16 to 23 show how the remember me feature works. When a valid login is found, the code checks if the remember feature is needed, if yes, a cookie is created with the new username, else previously existing cookies are deleted. The setcookie() method is used to create a cookie. this method takes three arguments which are Cookie name, value and expiration date. For the expiration date I used Time() + a number of seconds. Time() returns the number of seconds from the first Date which is (January 1 1970 00:00:00 GMT). To delete a cookie I used the setcookie() method with an already expired date. Values stored within coockies can be accessed using $_COOKIE["ItemName"]. In the login screen I added the following code:


1
2
3
4
5
6

<?php
if(isset($_COOKIE['User']))
{
header ('Location: coursework_2p2.php?Name=' . $_COOKIE["User"]);
}
?>

This code redirects the user to the welcome screen (second screen previously mentioned) without the need to re-login. The welcome screen contains a log out button that deletes the cookie and redirects the user back to the login screen.

Using Sessions


For task 2 we were asked to redesign the same system to use sessions instead of cookies. I decided to use cookies to store the first login date, and sessions to store the logged user. Sessions work a little bit different from cookies. Sessions must be started before the HTML tag with the function session_start().

To initialize a session variable you only have to use it as it were any other variable. For example $_SESSION['USER'] = "Mark" creates a session the the key 'User' and value 'Mark'. To destroy a session you must call the function session_destroy(). In my case I used the session_destroy() in the log out button. To convert my system from sessions to cookies I simply changed the parts with cookie methods, with the equivalent session statements. The table below shows how I changed lines 16 to 23 from the first table in task 2.



16
17
18
19
20
21
22
23

          if ($Remember == true)
             {
              $_SESSION['User']=$username;
              }
          else
             {
              session_destroy();
             }

Something new which I learned today and took me some time to figure out, was how to insert values in labels.   Finally I found this method which worked for me. I used it to show the first login date and time.


<label id="Label1" name="lblLoginTime"  > <?php if (isset($_COOKIE['LastLogin'])){ echo $_COOKIE['LastLogin'];}?></label>

Conclusion


PHP is very straight forward to use and has plenty of help available online. Although it differs from the kind of coding I am used to, I must say I enjoyed coding in PHP. PHP code can get quite messy, but I think if one uses good variable naming standards the problems occurring using loosely typed languages could be reduced. Particular attention must be given to Character Casing as if a variable is called mistyping a letter or Case of a letter, a new variable could be formed, without th programmer even noticing. Variable naming standards help avoiding these errors. I think if large websites like Facebook, manage to work using PHP, this language can be used practically for anything.

No comments:

Post a Comment