University of Bahrain

Information Technology College

Computer Science Department

Semester 1, Year 2006/2007

ITCS 373: Class Lab Work

PHP2

 

 

Instructor: Dr. Eshaa M. Alkhalifa

 

You should have completed all the exercises in PHP1 before starting this LAB session.

 

  1. We will continue to use HTML Kit for the PHP scripting in this advanced lab.  But don’t think that because it is called advanced that this would mean it would be any tougher than the previous lab because all functions will be explained in detail to you.
  2. DATE:   How can you get the correct date from the server and load that value into a variable?  Open a new document on HTML kit and write the opening and closing php tags and save it as Adv1.php in the correct directory.  Now go to the browser window and open your php file by writing localhost/Adv1.php and see today’s date.  Yes, that’s how easy this is.
  3. If you add the following two lines you will also get tomorrow’s date just by adding 1 using the operator +.

$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));

echo "<br>Tomorrow is ".date("m/d/y", $tomorrow);

  1. You can see the result of adding 1 to d.  There are many other variables that are used to store date items that you can use.
  2. INCLUDE:  This command is used to include a whole file as part of another file.  You may wish to place pieces of code that you use repeatedly as a file on their own and then include it into another file.  Open a new file and save it with the name aaa.php and copy the following code into it;

<a href="http://www.itcs.silvertair.com">Home</a> -

<a href="http://www.itcs.silvertair.com/course.php">Outline</a> -

<a href="http://www.itcs.silvertair.com/Forum">Forum</a> -

<a href="http://www.itcs.silvertair.com/assignments.php">Assignments</a> <br />

  1. Save your file and you back to the file called Adv1.php.  Add the line

 include("aaa.php"); immediately following the <?php line.

  1. If you get an error then perhaps you left extra lines in the aaa.php file.  It must contain nothing, other than the lines shown above.  The reason is that it is copied into the file Adv1.php so it does not need any tags to start the html or php etc.
  2. FILE:  You must be very careful when using files to avoid causing any damage by deleting important data or making a file so large to fill all the memory available.  You can create, open, close, write, read, delete, append, truncate files.
  3. CREATE/OPEN/CLOSE A FILE:  If a file does not exist, you just use the OPEN command to create it.  Notice that this gives errors in highly secure servers, so you may have to create it manually and then open it to use it for more security.  Add the following lines to your Adv1.php

$ourFileName = "testFile.txt";

$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");

fclose($ourFileHandle);

  1. Save your file at the correct location and open it.  You should not see any error messages but you should find the txt file in the same directory as your Adv1.php file.
  2. WRITE/READ/APPEND:  The line shown above has ‘w’ for WRITE.  We can use instead of this ‘r’ for READ a file or ‘a’ for APPEND.  You can also do more than one function at once by using ‘r+’ to READ and WRITE at the same time, and ‘w+’ to WRITE and READ at the same time, and ‘a+’ to APPEND and READ but notice that here the pointer is at the end of the file.
  3. You can add the following lines to your Adv1.php file to write to your file and to read from it.  Add these lines before the fclose and following the fopen commands.  Notice that you can change the file handle name to any name you wish but make sure it matches the one used to open the file.

$stringData = "Bobby Bopper\n";

fwrite($ourFileHandle, $stringData);

$stringData = "Tracy Tanner\n";

fwrite($ourFileHandle, $stringData);

  1. Now you can see your file contents by looking at the file http://localhost/testFile.txt in a browser window.  You can check you did indeed write to the file.
  2. Now you can add the following code following the fclose so that you open the file again and read from it.

$myFile = "testFile.txt";

$fh = fopen($myFile, 'r');

$theData = fread($fh, filesize($myFile));

fclose($fh);

echo "<br>",$theData;

  1. In this case I used fh instead of the file handle, but you can replace it by any word you wish as long as in both lines it is the same word.  You will also see the fread command used here to read from the file.  Following the file handle, you will find filesize($myFile) because this field allows you to write how long a string you wish to read from the file.  If you replace this with a number like 5 you will only get as output the first five characters from the file.
  2. Another function you test for reading from a file is $theData = fgets($fh); This one searches for a /n new line in the text file and gives the data that follows that.
  3. DELETE:  You just use the following lines to delete your test file

$myFile = "testFile.txt";

unlink($myFile);

  1. It is dangerous to include this type of code on a site because access from unauthorized people may allow them to delete important files without having proper permissions to be careful.
  2. TRUNCATE: If you wish to keep your text file but wish to delete all the information it contains as in the case of a log that is deleted once a week or so on you just open it and close it as follows;  Try it out.

$myFile = "testFile.txt";

$fh = fopen($myFile, 'w');

fclose($fh);

  1. Now if you check your text file, it should be empty, so if you wish to open a file that already has data and you wish to add data to it use ‘a’ instead of ‘w’.  Because ‘a’ adds to a file that already contains data.
  2. FILE UPLOAD:  In order to add a file upload ability to your site, you must have an XHTML script and a php script that will execute the upload instruction.  Write a new XHTML script that contains the following code;

<form enctype="multipart/form-data" action="uploader.php" method="POST">

<input type="hidden" name="MAX_FILE_SIZE" value="100000" />

<b>Choose a file to upload: </b>

<input name="uploadedfile" type="file" /><br />

<input type="submit" value="Upload File" />

</form>

  1. The enctype informs the php function of what type of file it will upload, and the input type is hidden to be able to associate a file size with the uploaded file so that visitors to your page are not allowed to upload files that are too large for what is possible or what you allow.  The second input is for the file itself.
  2. Now you can write a PHP code as follows in another file that you can call uploader.php.

<?php

$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

    echo "The file ".  basename( $_FILES['uploadedfile']['name']).

    " has been uploaded";

} else{

    echo "There was an error uploading the file, please try again!";

}

?>

  1. You must have a folder called uploads to place all your uploaded files into.  The next line specifies that you wish to place the file into that folder and you will get the file using the $_FILES.  You may remember the $_POST and $_GET commands from forms.  This command works in the same way.  You just give it two variables; one for the uploaded file’s name and the second for the name of the path on your computer that you upload the file from.  tmp_name is the name of the path to the temporary folder where the file will by stored for all upload and from which it is then copied to the location where you wish to find it.  In other words, PHP uploads all files to temporary folder on the server and then from there to the folder you specified.
  2. Make sure that you have a folder in your localhost location that is called uploads.  You can then test your code by opening a browser window and writing the name of a file that you wish to upload.  Click on upload and go to check if your file has been copied to that folder.
  3. COOKIES:  These are used to store information on the client computer if their browser settings for cookies are switched on.  The setting can be found on Tools/Options/privacy settings  you will find a slide bar that you raise to restrict cookies more or lower to reduce the level.
  4. Cookies are usually used to store information about the user on the user’s system.  This means you can store a variable, you can give the variable a value, and you can tell the client’s computer how long to keep the information before deleting it.
  5. Open a file and delete every single line in it.  Then copy the following to it and save it with the name and call it setcookie.php.  You can call it any name you wish, but here we will call it with this name.

<?php

$inTwoMonths = 60 * 60 * 24 * 60 + time();

setcookie("lastVisit", "my site is wonderful", $inTwoMonths);

?>

  1. Now open another new file and delete everything in it, then copy the following lines to it then save it with the name cookie.php.

<?php

if(isset($_COOKIE['lastVisit'])){

            $visit = $_COOKIE['lastVisit'];

  echo "The contents of your cookie are - ". $visit;}

else

  echo "You've got some stale cookies!";

   ?>

  1. Copy both your server directory. And open a browser window first and write localhost/setcookie.php.  You should see nothing there and not even error messages.  Then type localhost/cookie.php to see the contents of your cookie.
  2. An error that frequently occurs with cookies and even sessions, is when you place the setcookie line later in your code.  These commands must go with the headers, and if it is not at the top of your code you WILL get errors.
  3. SESSIONS:  Sessions are primarily used for security because you can use sessions to prevent users from going to a page unless they go through the login page first.  This is different from cookies because here the information is kept on the server and not placed on the client system.  It also means that you are less likely to have errors because of how your site visitor sets his security preferences on the browser.
  4. We will assume that we have a login page and then a page where users will see confidential data.  Open a new page on HTML kit and copy the following lines to it then save it as login.php.

<?php

session_start();

$_SESSION['views'] = 1; // store session data

echo "Pageviews = ". $_SESSION['views']; //retrieve data

?>

<br><br>

<a href="http://localhost /conf.php">Click here</a>

  1. You can also retrieve your session value using the following code, so add it to a new file and call it conf.php.

<?php

session_start(); 

if(isset($_SESSION['views']))

    $_SESSION['views'] = $_SESSION['views']+ 1;

else

    $_SESSION['views'] = 1;

echo "views = ". $_SESSION['views'];

?>

  1. Now open a browser window and type localhost/login.php, then click on the link and see where it takes you and what you see.  In the first page you should see Pageviews=1 and the link.  In the second page that the link takes you to you should see views =2 because it recognized the session and added 1 to it.
  2. Now open the conf.php file in a NEW browser window.  You will see the following views=1.  This means that this user did not go to the login page before coming here.  You can therefore add a simple redirect line by replacing all that appears after else with;

{$_SESSION['views'] = 1;

                        header("Location: http://localhost/login.php");}

  1. You must try it with a new browser window each time and you will notice that it immediately takes you back to the login window.  It only allows you to see the second page if click on the link on the login window.  So you will need session control for every page that you wish prevent users who did not log on from accessing.
  2. This brings you to the end of this lab.