Web Programming: Handling Files and Exceptions
Web Programming: Handling Files and Exceptions
Web Programming: Handling Files and Exceptions
XML
Universal way to Application 1 Application 2
exchange structured JSON
data, e.g. JSON, XML
Exchanging tabular
CSV Spreadsheet
data – CSV Database
File function examples
file_get_contents, Reading / writing files
file_put_contents, file,
fopen, fgets, fgetcsv,
feof, fwrite, fputcsv,
fclose
Application 1 writes
a file of employee employees
Application 2 reads
details and makes
the file
it available to
application 2
Writing data to a file
We can use: fwrite
You need to open the file with a mode that permits
writing
Open file in append writing mode
Example
$fileHandle = fopen("employees.txt", "ab");
$employee = "Another person";
$dept = "MCE";
Add new
fwrite($fileHandle, "$employee|$dept".PHP_EOL);
line
fclose($fileHandle);
Function, error_log_file.log
e.g., log_error($e) Date/time of error|error details
Date/time of error|error details
Write error date/time Date/time of error|error details
and error details to Date/time of error|error details
a file …
fopen file modes
The first argument to fopen is the name of
the file you want to access
The second is the file mode. These include
Mode Action(s)
rb Reading from the beginning of a file
rb+ Reading and writing from the beginning of a file
wb Writing from the beginning of a file
wb+ Reading and writing from the beginning of a file
ab Writing from the end of a file
ab+ Reading and writing from the end of a file
try {
echo divide(4, 0);
} catch (InvalidArgumentException $e){
// Take some appropriate action
} catch (RangeException $e){
// Take some appropriate action
} catch (Exception $e){
// Handle any other exceptions
} finally {
// Put code here that will always run
}
Handling uncaught exceptions
We should always include try/catch around any code that may throw an
exception. However, its hard to do perfectly
So, set a global exception handler as a safety net
To do that you can create a custom exception handler function, e.g.,
if(!file_exists("employees.txt")) {
throw new ErrorException("Couldn't open file");
}
$fileHandle = fopen("employees.txt", "rb");