Thursday, 28 April 2011

Coursework2 - Building a Web Space Management System

In this blog post, I will be discussing about my experience in building a web space management system where the user can register, login, upload files, delete files, create directories and delete directories.

SQL Injection

SQL injection is a security vulnerability which occurs in the database. An SQL injection may occur when the input of the user is not for filtered escape characters. A method to avoid SQL injection is by using the mysql_real_escape_string() function, as shown in lines 25-26. For more details on SQL injection one can look at http://php.net/manual/en/security.database.sql-injection.php
23:  $user = $_POST["username"];  
24:  $pass = $_POST["password"];    
25:  $user = mysql_real_escape_string($user);  
26:  $pass = mysql_real_escape_string($pass);  

Registration

This page is used so that a user can register to create an account by inserting the username, email and password into a form. The user will retype the password to confirm the password created. When the user presses the ‘Register’ button, the username, email and password will be inserted into the database. The code to insert into the database is inserted into another file ‘register.php’. In this page, a connection to the database was done, as described in the previous post and an insert statement have been created.
42:  $sql="insert into users (name,email,password)values('$rname', '$remail', '$rpass1')";  
If the data is invalid or the passwords do not match, it will be redirected to the registration page.

Login

The login page consists of a form 'login.php' where the user will insert the username and password. The data of the form will be submitted to 'loggedin.php'.
22:  <form action="loggedin.php" method=post>  
An explanation about the login page has been written in the previous three posts. Once the user is logged in, the user can create and delete directories, upload files and delete files. This is how the logged in page looks like:

Logged in Page

Creating Directories

To create a directory, a form has been created where it will be submitted to the php file 'dir.php'. The form consists of a text field and a submit button, whereas the php file consists of the function mkdir(), to create the directory.
41:  if (!mkdir($create)) {  
42:    die('Failed to create directory');  
43:  } else {  
44:    echo "Directory Successfully Created";  
45:  }  
Lines 41-45 shows that if the directory cannot be created (!mkdir($created)), a message that the creation of the folder is failed will appear, otherwise a message that the directory is created will appear, and the directory will be created.

Uploading Files

The page loggedin.php, also consists of a form where the user can upload files. Once the files is uploaded, the details of the files (the file name, file type and file size) will be appeared on the page, using the following code:
69:   move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],   
70:   "C:/xampp/htdocs/assignment/$user/" . $_FILES["fileToUpload"]["name"]);  
71:   echo "File Uploaded:" . $_FILES["fileToUpload"]["name"]."<br>";  
72:   echo "File Type:" . $_FILES["fileToUpload"]["type"]."<br>";  
73:   echo "Total size : ".$s."<br>";  
The files uploaded will be saved in a temporary folder, but the file can be moved into another folder using the function move_upload_file(), where the file to be moved and the new location will be specified, as shown in line 30.

Delete Files and Directories

The 'loggedin' file also contains a list of files and directories inside a particular folder. Near each item (file and directory), a checkbox have been created so that when the checkbox is ticked and the delete button is clicked, the file or directory will be deleted. This was done using the unlink() function to delete files and using rmdir() function to delete directories.
1:  if (is_file($myFile)){  
2:    unlink($myFile);  
3:    echo "File $myFile successfully deleted <br>";    
4:  } elseif (is_dir($myFile)) {  
5:    rmdir($myFile);  
6:    echo "Directory $myFile successfully deleted <br>";  
7:  }  

Users only able to access their Own Space

For users to access only their space, a directory (folder) was created for each user, where the name of the folder is the same as the username, and the username is unique for each user. In this case, the usernames are all different, and a folder is created manually.
88:    if ($handle = opendir("./$user")) {  
89:      //code  
98:    }  
Line 88 shows that when the user logs in, a folder will be opened depending who the user is. As a future improvement, I thought that when the user registers, if the name already exists, the user will have to register with another name. Also, when the user registers, a folder will be created automatically, according to the user's username using the mkdir() function.
 mkdir($user);  

Space Limits

The code below shows what it should do when the size exceeds. The getDirectorySize() function is a function which was created to get the size of the directory. If the size of the directory is larger than 52428800 bytes, a message that the size have exceeded will be displayed.
46:  $path="C:/xampp/htdocs/assignment/$user/";  
47:  $dirsize=getDirectorySize($path);
48:  $s1=$_FILES["fileToUpload"]["size"] ;
49:  $s=$dirsize['size'];
50:  $s2= $s+$s1;
51:  if ($s2 > 52428800){
52:    echo "Size exceeded";    
53:  }
When I tested it I found out that the size of the uploaded file will be incremented after uploading the next file or else after refreshing the page. That is, if the size will be exceeded in the previous file, that file will be uploaded, but for the next file it will display that the size have exceeded and the file will not be uploaded. To overcome this, I had to add the code found in lines 48 and 50. The following line of code is found inside the getDirectorySize() function.
38:  $totalsize = filesize($nextpath) + $totalsize;  

When Size Exceeds

Problems Encountered

One problem which I had when creating this system is when I used the unlink() function to delete files. When I clicked on the delete button, all the files inside that folder were deleted, both when ticking on the checkboxes and when leaving them unticked.
The problem was when creating the form to include the checkboxes in the list. At first, I created a form using html, but in order for this to work, this has to be created using php.
88:    if ($handle = opendir('./$user')) {  
89:      $i=0;  
90:      while (false !== ($file = readdir($handle))) {  
91:      if ($file != "." && $file != ".." && $file != "delete.php") {  
92:      echo "<input type=\"checkbox\" name=\"deletefile[$i]\" value=\"$file\" />";  
93:      echo "<a class=\"alog\" href=\"upload/\".$file>$file</a><br>\r\n";  
94:      $i++;  
95:        }  
96:      }  
97:      closedir($handle);  
98:    }  
A variable 'i' is declared, with the value of 0 assigned to it as shown in line 89. In the input tag of the form (where the type is checkbox), the name consists of an array (deletefile[$i]), where the value of $i is incremented, each time an item is added, to add a checkbox using the while loop. More details on http://www.hotscripts.com/forums/php/31146-deleting-multiple-files-using-checkboxes.html

The opendir() function (line 88) is used to open a directory handle. The readdir() function (line 90) is used to read from a directory handle. The closedir() function (line 97) is used to close a directory handle.

Another problem which I had was when deleting a directory. When I deleted a file, the file was successfully deleted, but when I tried to delete a directory, it gives me an error that the permission is denied. This was because I was using the unlink() function, both to delete a file and also to delete a directory. To delete a directory, the function rmdir() should be used.

Some of the files contain a "Back to previous page" button, where the user can go back to the previous page. Every time the user has to click on this button, the page should be reloaded.

Testing on a mobile

The system have also been tested on my mobile (Nokia 5800), which supports wifi. Since the webspace management system is hosted locally, it can be viewed from another computer (in this case my mobile), by using the IP address. When I styled this, I gave the div container a width of 700px , but when I looked on my mobile, I had to scroll from left to right. Therefore, I changed the width of the container to percentage (%) instead of pixels, to fit to screen as shown in line 35:
34:  #container {  
35:       width: 80%;  
36:       margin: 0px auto;  
From my mobile, I also registered, logged in, uploaded files, created directories, deleted directories and deleted files. One thing I found out when testing on my mobile is that the alert box 'Invalid Username/password combination' will appear when the 'Back to Previous Page' button is clicked. This might be because the mobile phone does not support javascript. Instead, the browser's back button can be used.

Uploading files from mobile to computer is another alternative to transfer files, instead of using Bluetooth or a USB cable.

References

http://www.hotscripts.com/forums/php/31146-deleting-multiple-files-using-checkboxes.html
http://php.net/manual/en/security.database.sql-injection.php
http://www.go4expert.com/forums/showthread.php?t=290

Wednesday, 20 April 2011

Week 9 - More PHP (Databases)

During the last lesson, we learned more on PHP, this time using databases.

Database

A database is used to store data, using tables. The following are SQL commands which are commonly used:

CREATE – to create tables within the database
INSERT – to add data inside the tables
SELECT – to view data
DELETE – to remove data
UPDATE – to modify data
DROP – to delete tables

PHP and MySQL

In PHP one can interact to a database using the mysql_connect command:
 mysql_connect(server, username, password)  

Lab Session

During the lab session, the following tasks have been given:
  • Log into the SQL server using command line and perform some commands such as listing the databases
  • Attempt to connect to SQL by using PHPMYADMIN
  • Create a database that stores usernames and passwords
  • Modify your PHP program from the previous lab session to connect to the database to authenticate the user

Logging into the SQL server

To log into the the SQL server using command line:
  1. Open command line prompt
  2. Then if you have C:\Users\Name write cd ..\..\
  3. Then the foldercd C:\XAMPP\mysql\bin was opened and the command mysql -u root -p and the datapase password have been entered.
  4. To show a list of databases, the show databases; command have been inserted.

phpMyAdmin

phpMyAdmin is used to administer MySQL over the web.

phpMyAdmin

Creating database

A database that stores usernames and passwords have been created, where I used a GUI Tool named Workbench.
1:  create database `usersdatabase`;  
2:  DROP TABLE IF EXISTS `usersdatabase`.`usertable`;  
3:  CREATE TABLE `usersdatabase`.`usertable` (  
4:   `UserID` int(10) unsigned NOT NULL AUTO_INCREMENT,  
5:   `UserName` varchar(45) NOT NULL,  
6:   `Password` varchar(45) NOT NULL,  
7:   PRIMARY KEY (`UserID`)  
8:  );  
Records have been inserted into the database using the INSERTcommand. To view data, the SELECT command is used.

Modification of PHP program

In the previous post, an associative array was created to store the usernames and password. In this post, a database have been created to store the usernames and password.
To connect to the database the php code shown in lines 12-13 is used
12:  $con = mysql_connect("localhost","root","");  
13:  mysql_select_db("usersdatabase", $con);  
If the connection from the database will fail, the code shown in line 17 is used
17:  die('Could not connect: ' . mysql_error());  
Lines 20-24, a variable named $result is used to execute a query to select from the table where the username and password will be what the user inserted in the form. Line 21 will calculate the number of rows the $result variable has. If the result is not zero, a welcome message will appear. If the user checks on the 'Remember Me' checkbox, a cookie will be created. If the username and password does not match and alertbox that it is invalid will appear.
20:  $result = mysql_query("SELECT * FROM usertable where UserName=\"$user\" and Password=\"$pass\"");  
21:  $row = mysql_numrows($result);  
22:  if($row !=0)  
23:  {  
24:  echo ("Welcome $user");  
The rest of the code is the same as found in the last post. In my next post I will be discussing about MySQL injection and about the next coursework.

Sunday, 10 April 2011

Week 8 - More PHP

In this week's lecture, cookies and sessions in PHP have been introduced

An html page (login2.html) has been created which consists of a form where a user can enter the username and password in the fields.
1:  <form action="login.php" method=post>  
Action is used so that the submit button can send data to a server. Then the data is sent to the page specified, which is “login.php”. Methods “post” and “get” are used to specify how to send the data of the form. “Post” is more secure than “get”, because “get” adds the data to the URL.

The isset() function checks whether the variable given exists or not. The $_POST function will collect the form data. In lines 6 and 7, variables $user and $password have been declared.
6:  $user = $_POST["username"];  
7:  $pass = $_POST["password"];
An associative array has been created to store the values of the username and password. Line 13 will check whether the username and password that the user inputs are correct. If it is validated, that is, the username and password matches from the associative array, a welcome message with the username will be appeared.
12:  $pswd = array("Stephanie"=>"password1", "John"=>"password2", "Mary" =>"password3", "Joe"=>"password4", "Alesha"=>"password5");  
13:  if(isset($pswd[$user])) if($pswd[$user]==$pass) $validated = true;  

When the username and password do not match, the “login.php” page will be redirected to “login2.html”, using the below line of code.
26:  header("Location: login2.html");  
I wanted that an alert box will appear first which will say “Invalid User Name/Password Combination”. This could not be done when using header (“Location: login2.html”). This was achieved using JavaScript’s alert() function and window.location, as shown in lines 27-28
27:  echo "<script type=\"text/javascript\">alert('Invalid UserName/Password combination');".  
28:     "window.location = 'login2.html'</script>";   

Cookies

A cookie is used for user identification. It is used to store user preferences, which must be encrypted. To create a cookie, the setCookie() function is used, which consists of parameters 'name', 'value' and 'expire'.

Cookies have been created both for the username and password, where the expire time is set to 3600 (which will expire in one hour). To delete a cookie, instead of +3600, -3600 should be inserted.
16:  setcookie("username", $user, time()+3600);  
17:  setcookie("password", MD5($pass), time()+3600);   
For the password, a cryptographic Message Digest Algorithm (MD5) is used.

Without MD5

With MD5

To retrieve a cookie value, $_COOKIE is used:
2:  $user = $_COOKIE["username"];  
3:  $pass = $_COOKIE["password"];  
4:  echo "WELCOME $user";

cookie in phpinfo() report

Welcome $user

After 1 hour

Sessions

Sessions are used to maintain persistent data between pages throughout a Web site. To start up a session, the following function needs to be inserted before the html tag:
1:  <?php  
2:  session_start();  
3:  ?>  
For storage and retrieval of session variables, the $_SESSION variable is used
6:  $_SESSION["username"]= $user;  
7:  $_SESSION["password"]= $pass;  
8:  echo "Username=". $_SESSION["username"]."<br/>";   
9:  echo "Password=". $_SESSION["password"];   
To destroy a session, both the unset() function and session_destroy() function can be used.
13:  unset($_SESSION["username"]);  
14:  session_destroy();  

Wednesday, 6 April 2011

Week 7 - Introduction to PHP

In this week's lesson, PHP have been introduced and the following tasks have been given:
  • Using your browser, verify that PHP is working on your web server.
  • Create an associative array of user names and passwords and list the entire array in a table.
  • Explain the difference between the echo() and print() functions.

Testing PHP

Last week to verify that PHP is working I created a file named hello.php that have a phpinfo function (line 4). I added an additional line where a heading "PHP info Report" will be shown at the center of the page before the php info report.

Associative Arrays

An associative array of user names and passwords have been created where the entire array was listed in a table. Associative arrays allows access through keys and are used to access many important values in PHP, Moseley (2007)[1].


Difference between echo() and print() functions

The print function always return 1 as a value but can be ignored, while echo is faster because it will not return 1 as a value, Moseley (2007)[1]. Also the echo function can take more than one expression, while the print cannot as discussed in
http://community.invisionpower.com/topic/166459-php-difference-between-echo-and-print/.

[1] Moseley, R. (2007) Developing Web Applications.