Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 7

PHP handling files and exceptions workshop

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.

Exercise: pre-task - setting global exception and error handlers


We will set global exception handlers as safety nets to handle any uncaught exceptions and errors
(ensuring that the latter, which may be caused by some php code that does not use exceptions, are
brought within the exception handling system).
1. Add the following code to your functions.php script. You could obviously vary the action
taken by the exceptionHandler function, for example by changing the message

/**
* 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

Hint: one way to do this is to:


 first store the date and time that the error occurred in a variable, say
$errorDate. For example, $errorDate = date('D M j G:i:s T Y');
 second store the error details from $e->getMessage() in a variable, say
$errorMessage. For example, $errorMessage = $e->getMessage();
 third, as any line breaks inside the error details will cause problems when later trying to
read errors from the file (as line breaks are used to separate ‘records’), use the following
lines of code to remove them
$toReplace = array("\r\n", "\n", "\r"); //chars to replace
$replaceWith = '';
$errorMessage = str_replace($toReplace, $replaceWith,
$errorMessage);
 Finally put $errorDate, followed by a |, then $errorMessage and then PHP_EOL
into fwrite (see the lecture slides for a similar example)

d. Close the file using fclose

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,

Thu Oct 31 13:17:34 BST 2019|SQLSTATE[42S02]: Base table or view not


found: 1146 Table 'unn_izge1.nc_m' doesn't exist

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.

Exercise 2: reading a file and displaying its contents


In this exercise, you will read data from a file and output it to a browser.
1. Create a new PHP script (remembering as always to use the basic HTML core tags as a
basis) to read data from your error_log_file.log (see exercise 1) to retrieve details of
any error messages logged in it and display them in a web browser. It will need to do the
following

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.

Exercise 3: writing database data into a CSV-formatted file


In this exercise, you will retrieve data from a database and write it as CSV-formatted data to a file.
You would typically do this to exchange data with another application that needed it in tabular form.

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)

a. Make a database connection


b. Use fopen to open the CSV file called students.csv, in reading mode e.g.,
$fileHandle = fopen("students.csv", "rb");
c. Set-up an SQL statement to insert a new record into the copy_student table with named
PDO placeholders for studentid, forename, surname, coursecode, stage and email and
prepare the statememt
d. Iterate through the csv file students.csv line by line
e. For each iteration (line) in the file
i. use fgetcsv to read the line and store it in a variable, e.g., $data. For example
$data=fgetcsv($fileHandle);

As fgetcsv returns data as a numerically indexed array, $data will be such as


array. So its parts can be accessed as ana rray element, e.g., $data[0]
i. if $data has content then, insert the contents of $data (the line of the file) as a
database record using the PDO execute method passing it values for studentid,
forename, surname, coursecode, stage and email. For example, use $data[0] for
studentid $data[1] for forename etc.
f. Display a message saying that the database table copy_student has been created
g. Handle exceptions

Exercise 5: choosing a table(s) to export to csv


In this exercise, you will create a PHP script that allows the user to choose a database table(s) to
query and export data from to create a CSV formatted file(s).
The script should create a form web that contains one checkbox for each of the tables in your
database (e.g. srs_student, srs_course etc.). Rather than hard coding the required check
boxes, the code should instead create these dynamically by querying the database to retrieve the
names of all of the tables in the database, and then build a checkbox for each table.
The form should allow the user, by ticking the required checkboxes, to select which database table(s)
they want to export to a CSV file(s).

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

2. Test your new script by viewing it in a web browser. It


should look something like that shown opposite:

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)

a. Make a database connection


b. Retrieve the array of the user’s choice of table names (one for each of the checkboxes that
were selected by the user in the web form) from the request stream sent from
csvExportForm.php when the user clicked the submit button
c. Iterate (loop) through the array of table name choices (Hint: you could use a foreach for
this). For each element in the array call a function named output_csv (you will make this
next). Pass two arguments to it, the table name (the current one in the loop, e.g.,
srs_course) and the database connection handle (e.g. $dbConn)
d. Create the output_csv function. It will need to do the following
i. Accept two arguments, the table name and the database connection handle (e.g.
$dbConn)
ii. Open a connection to a file those name is the value of the table name argument
with .csv on the end (e.g., srs_course.csv)
iii. Query the database table whose name is the value of the table name argument (e.g.,
srs_course) using SQL and PDO to retrieve the values of each field for each record.
Hint: as you won’t know in advance what the table field names are think about the
SQL you could use to select all of the fields in a table
iv. Iterate over the query results set with a while loop
v. For each iteration (record) write the data as a CSV-formatted string to the file
vi. Close the csv file
vii. Display the table name in the browser and a message saying that its records have
been written to a file (include the filename)
viii. Handle exceptions

Page 7 of 7

You might also like