Professional Documents
Culture Documents
Workshop - Handling Files and Exceptions
Workshop - Handling Files and Exceptions
In this workshop, you look at handling files and exceptions. You will:
create global exception handler and global error handler functions
create a function to write error messages to a file like in a production system
read error messages from a file and display them in a browser
retrieve data from a database and write it as CSV-formatted data to a file
read data from a CSV-formatted file and write it to a database
apply exception handling in general
In the following exercises remember that you will then need to upload copies of each file you create onto your
web space on the newnumyspace web server and that to test them you need to enter the appropriate web
address into the address bar of your web browser.
/**
* define a function to be the global exception handler that
* will fire if no catch block is found
* @param $e
*/
function exceptionHandler ($e) {
echo "<p><strong>Problem occured</strong></p>";
log_error($e);
}
/* now set the php exception handler to be the one above */
set_exception_handler('exceptionHandler');
/**
* define a function to be the global error handler, this will
* convert errors into exceptions.
*/
function errorHandler ($errno, $errstr, $errfile, $errline) {
// check error isn’t excluded by server settings
if(!(error_reporting() & $errno)) {
return;
}
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
/* now set the php error handler to be the one above */
set_error_handler('errorHandler');
Note that our global exception handler will display a user-friendly message to the browser and
use the log_error function that you will make in exercise 1 to write error details to a log file.
Page 1 of 7
Exercise 1: create a function to log errors to a file
In a system under development, it is wise to output detailed error messages to the browser to aid
debugging. However, a production system should instead only display more “user friendly” messages
to the browser and log detailed error messages with technical details to an error log file. In this
exercise, you will create a function to do the latter and add it to your functions.php script. The
function can be used (called) in the catch block of a try, catch of a different script where an
exception may occur (for example, in chooseMovieList.php).
1. Create a function called log_error and add it to your functions.php script. It should:
a. Accept one parameter, the error details (e.g., $e)
b. Use fopen to open a file called error_log_file.log in ‘ab’ mode (as we want to
add errors to the end of the file, so that new ones don’t overwrite older ones)
c. Write a line to the file using fwrite that includes
i. the date and time that the error occurred. To get the date and time you can use
the date function – see below
ii. followed by a delimiter like a ‘|’
iii. the error details from $e->getMessage() – see below
iv. and PHP_EOL to add a new line to put each error on a new line
Page 2 of 7
2. Modify a php script that you created earlier that used try, catch for exception handling (say
chooseMovieList.php that you made in week 1) as follows:
a. Change the catch block
i. So that it only displays a “user friendly” error message like “A problem
occurred. Please try again.” to the browser
ii. To call your log_error (e.g. log_error($e); ) function to log the details of any
error that occurs
b. Change the script (e.g., chooseMovieList.php) to include a deliberate error. For
example, in the case of chooseMovieList.php, miss-spell the name of a database
table, say change nc_movie to nc_m. That should cause the try block to raise an
exception that will be detected by your catch block which will be passed to log_error
for logging
3. Test your modified php script (e.g., chooseMovieList.php) and check whether your error
logging function worked. To do that use FileZilla and look to see if the
error_log_file.log file has been added. If so, drag a copy over to your U drive and open
it from there. You should see that the date/time of the error and the error message has been
added. For example,
Note that in a production system you would ensure that all of your scripts logged
detailed error messages to a log file and only displayed “user friendly” messages to
the user.
a. Use fopen open the file called error_log_file.log in the ‘rb’ reading mode
b. Iterate through each line of the file of error details using a while loop provided that we have
not reached the end of the file
i. use fgets to read the line and store it in a variable, e.g., $message
ii. if $message has content then
use trim to trim the newline character from $message
use explode to split the contents of $message on the | character (the
delimeter) into an array of message parts (the date/time that the error
occurred and the error message details)
generate html to display the parts of the message to the browser
c. Close the file using fclose
d. Handle exceptions
Note that the lecture slides provide a similar example that you can adapt for this task.
Page 3 of 7
Directed learning
If you have time in the workshop attempt the following exercises, otherwise attempt them as directed
learning. Please note that these tasks are not related to the assignment, but are provided for those
who want to explore handling csv files.
1. First, download from blackboard a copy of the file CourseStudent.sql and import it using
the phpMyAdmin interface. This will create a table called srs_student that we will have the
following fields and 308 student records. A table called srs_course will also be created.
2. Create a new PHP script (remembering as always to use the basic HTML core tags as a
basis) to retrieve data from a database table srs_student and write it as CSV-formatted
data to a file using fputcsv. It will need to do the following: (please copy the steps below and
make them into comments, then write your code beneath each one)
a. Open a CSV file called students.csv, in writing mode (if the file doesn’t exist it will be
created), e.g.,
$fileHandle = fopen("students.csv", "wb");
b. Make a database connection
c. Query the database srs_student table using SQL and PDO to retrieve the studentid,
forename, surname, coursecode, stage and email for each student record
d. Iterate over the query results set with a while loop using fetch(PDO::FETCH_NUM) –
as fputcsv needs a numerically indexed array -, e.g.,
while ($row = $stmt->fetch(PDO::FETCH_NUM))
e. For each iteration (record)
i. write the data as a CSV-formatted string using fputcsv, e.g.,
fputcsv($fileHandle, $row);
ii. generate html to display the record’s student ID, forename, surname, coursecode,
stage and email address to the browser. Note that as you are retrieving the records as
a numerical array, you will need to access the record’s fieldname value by numerical
position. For example, $row[0] for studentid, $row[1] for forename etc.
f. Use fclose to close the csv file
g. Display a message saying that the records have been written to the file
h. Handle exceptions
Page 4 of 7
Exercise 4: reading a CSV file and writing it to a database
In this exercise, you will read data from a CSV-formatted file and write it to a database. You would
typically do this to exchange tabular formatted data with another application that needed it. To
simulate this you will read from the students.csv file that you created earlier and write it to a copy
of the srs_student database table called copy_student.
1. First, download from blackboard a copy of the file copyStudent.sql and import it using the
phpMyAdmin interface. This will create a table called copy_student that will set-up a copy
of srs_student table but without any records
2. Create a new PHP script (remembering as always to use the basic HTML core tags as a
basis) to read data from a CSV-formatted file using fgetcsv and write it to the
copy_student database table. It will need to do the following: (please copy the steps below
and make them into comments, then write your code beneath each one)
1. Create a new PHP script called csvExportForm.php (remembering as always to use the
basic HTML core tags as a basis) to query your database to get the names of the tables in it
and then use that data to create a checkbox for each table. It will need to do the following:
(please copy the steps below and make them into comments, then write your code beneath
each one)
Page 5 of 7
a. Start a new form whose action is to call a script named csvExportProcess.php
b. Make a database connection
c. Query the the database using the SQL “SHOW TABLES” to return all of the tables available in
your database. There will only be one field in the record resultset and that will be called
Tables_in_databasename – here you should substitute databasename with the name of your
own database (e.g. unn_w16000000)
d. Iterate through the query results (the table names) creating the html for a checkbox for each
table name. Hint: Name each checkbox chk[] – this will mean that when a user checks a
checkbox, its name will be placed in an array that you can process later. Set the value of the
checkboxes to the name of the table that they represent
e. Add a submit button to the form
f. Close the form
g. Handle exceptions
Page 6 of 7
Exercise 6: processing the user’s choice of table(s) to export
In this exercise, you will create a PHP script that processes the user’s choice of database tables and
create CSV files for them.
1. Create a new PHP script called csvExportProcess.php (remembering as always to use
the basic HTML core tags as a basis) to process the user’s choice of table(s) to create one
CSV file (e.g. srs_student, srs_course etc.) for each of the tables that the user has
selected to export data from. It will need to do the following: (please copy the steps below and
make them into comments, then write your code beneath each one)
Page 7 of 7