SakhaliaNetHome PageMilitary HistoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Files (II)

PHP Example #102

Reading parts of files

This example reads a list of e-mail adresses and names and prints a list of mailto:links for each of the entries in the file. The function fgets() opens a connection with the file and returns a variable that allows to access the file for subsequent operations. In the first parameter passed to fgets() which is the path of the file, use / instead of \ even if the path corresponds to a local computer. The second parameter indicates which operation we want to perform on the file; the table with the different values can be seen in the reference pages.

The function fgets() reads a line in the file and returns it as a string (its position in the file is automatically kept by the PHP interpreter). The function feof() returns true if the marker that fgets() uses has reached the end of the file; remember that you should hit Enter after the last entry on the file, to ensure that a blank line is created at the end of the file, a line that will be recognized as the end of the file, otherwise the last entry on the file could not be retrieved. Finally, the function fclose() closes the connection with the file.

<?php
$fh = fopen('people.txt', 'rb');
for ($line = fgets($fh); ! feof($fh); $line = fgets($fh)) {
$line = trim($line);
$info = explode('|', $line);
print '<li><a href="mailto:' . $info[0] . '">' . $info[1] . "</a></li>\n";
}
fclose($fh);
?>

// Content of the file people.txt (this comment is not included)
alice@example.com|Alice Liddell
bandersnatch@example.org|Bandersnatch Gardner
charles@milk.example.com|Charlie Tenniel
dodgson@turtle.example.com|Lewis Humbert

PHP Example #103

Writing parts of files

Once a file is opened in a mode that allows writing, we can use the function fwrite() to write something in the file. In this example fwrite() writes in a file called dishes.txt the data recovered from a table called dishes stored in a database. Since fwrite() doesn't add a new line automatically at the end of the string, to write in separated lines we add \n at the end of the string.

<?php
// Connects with database
$db = mysqli_connect('insert_hostname_here','insert_username_here',
'insert_password_here','insert_databasename_here');
if (! $db) { die("Can't connect: " . mysqli_connect_error()); }
// Opens dishes.txt
$fh = fopen('dishes.txt', 'wb');
$sql = 'SELECT dish_name, price FROM dishes_2';
$q = mysqli_query($db, $sql);
while ($dish = mysqli_fetch_object($q)) {
// Writes each line (with a line break at the end) in dishes.txt
fwrite($fh, "The price of $dish->dish_name is $dish->price \n");
}
// Closes dishes.txt
fclose($fh);
print 'Link to the file: <a href="dishes.txt">dishes.txt</a>';
?>
Link to the file: dishes.txt

PHP Example #104

File checking and permissions

PHP offers functions to determinate what can be done and what not with a certain file. The function file_exists() allows to check if a certain file or directory exists. The functions is_readable() and is_writeable() allow to check if we can read from or write to a file.

<?php
// Checking if a file exists
print 'Checking if a file exists: ';
if (file_exists('index.php')) {
print 'Index file is present.';
} else {
print 'Index file is not present.';
}
// Checking if a file has reading permission on
print '<br/>Checking if a file has reading permission on: ';
$template_file = 'page-template.html';
if (is_readable($template_file)) {
$template = file_get_contents($template_file);
print 'The template file can be read.';
} else {
print "Can't read template file.";
}
// Checking if a file has writing permission on before adding a line to it
print '<br/>Checking if a file has writing permission on: ';
$log_file = 'login.log';
if (is_writeable($log_file)) {
$fh = fopen($log_file, 'ab');
fwrite($fh, $_SESSION['username'] . ' at ' . strftime('%c') . "\r\n");
fclose($fh);
print 'The log file can be written.';
} else {
print "Can't write to log file.";
}
?>
Checking if a file exists: Index file is present.
Checking if a file has reading permission on: The template file can be read.
Checking if a file has writing permission on: The log file can be written.

PHP Example #105

Checking errors

Until here, the examples have been shown without code for checking errors, for brevity reasons. Despite they work, they are somehow incomplete, for working with files supposes an interaction with external resources. This means that we should take care for anything that can cause problems, such as the file permissions of the operating system or a disk that depletes its space.

In practice, for writing a robust code for managing files, we should check the value returned by every function that is related with the file; each of them generate a warning message and return false if there is a problem. If the configuration directive track_errors is activated, the text of the error message will be available in the global variable $php_errormsg. This example shows how to check if fopen() or fclose() find an error.

<?php
// Connects with database
$db = mysqli_connect('insert_hostname_here','insert_username_here',
'insert_password_here','insert_databasename_here');
if (! $db) { die("Can't connect: " . mysqli_connect_error()); }
// Opens dishes.txt
$fh = fopen('dishes.txt', 'wb');
if (! $fh) {
print "Error opening dishes.txt: $php_errormsg";
} else {
$sql = 'SELECT dish_name, price FROM dishes_2';
$q = mysqli_query($db, $sql);
while ($dish = mysqli_fetch_object($q)) {
// Writes each line (with a line break at the end) in dishes.txt
fwrite($fh, "The price of $dish->dish_name is $dish->price \n");
}
// Closes dishes.txt
if (! fclose($fh)) {
print "Error closing dishes.txt: $php_errormsg";
}
}
?>

PHP Example #106

Checking errors in file_get_contents()

The following examples show how to check errors when using other file managing functions that are not fopen() or fclose(). While with these the operator ! was enough to check the returned value, with other functions we have to check if the returned value is strictly false and not something that just evalues as false; for such, we use the operator === that compares two values and considers them to be equal if they have the same value and also are of the same type.

<?php
// Checking errors in file_get_contents()
$page = file_get_contents('page-template.html');
if ($page === false) {
print "Couldn't load template: $php_errormsg";
} else {
// Inserts the title of the table
$page = str_replace('{title}', ':: WELCOME ::', $page);
// Sets the color of the cell to be blue or green depending on time
if (date('H' >= 12)) {
$page = str_replace('{color}', 'blue', $page);
} else {
$page = str_replace('{color}', 'green', $page);
}
// Takes the user name and login time from a previously saved session
$page = str_replace('{name}', $_SESSION['username'], $page);
$page = str_replace('{time}', $_SESSION['logintime'], $page);
// Prints the results
print $page;
} ?>

:: WELCOME ::

Hello, 54.211.200.222

You have connected at 08:43 AM