Chapter Four Files and Directories
Chapter Four
4. Files and Directories
4.1. Reading files/ Directories
Files and directories have three levels of access: User, Group and Other. The three typical
permissions for files and directories are:
Read (r)
Write (w)
Execute (x)
A stream is a channel used for accessing a resource that you can read from and write to. The
input stream reads data from a resource (such as a file) while the output stream writes data to a
resource. In file operation, we do have the following steps or procedures:-
1. Open the file stream with the fopen() function
Syntax:- variable= fopen(“text file”, “mode”); where mode mean r, r+, w, w+ etc as
shown in the next page.
2. Write data to or read data from the file stream
We use fread(($filepointer,”filesize”) function to read files or data.. We can also use
fgets() function to read files or data. It is written with two parameters like
fgets($filepointer,”filesize”)
o Reads up to $bytes of data, stops at newline or end of file (EOF)
PHP supports two basic functions for writing data to text files:
o file_put_contents() function writes or appends a text string to a file. Its syntax for
the file_put_contents() function is: file_put_contents (filename, string[, options]
o fwrite() function incrementally writes data to a text file. Its syntax for the fwrite()
function is: fwrite($handle, data[, length]);
3. Close the file stream with the fclose() function:- used when finished working with a file
stream to save space in memory.
Syntax:- fclose(file name that contains the opened files);
Example:- $handle = fopen('people.txt', 'r');
while (!feof($handle)) {
echo fgets($handle, 1024);
echo '<br />';
Page 1 of 13
Chapter Four Files and Directories
} fclose($handle);
Files modes can be specified as one of the six options in this table.
Mode Purpose
r Opens the file for reading only. Places the file pointer at the beginning of the file.
Opens the file for reading and writing. Places the file pointer at the beginning of the
r+
file.
Opens the file for writing only. Places the file pointer at the beginning of the file
w and truncates the file to zero length. If files does not exist then it attempts to create a
file.
Opens the file for reading and writing only. Places the file pointer at the beginning
w+ of the file and truncates the file to zero length. If file does not exist then it attempts
to create a file.
Opens the file for writing only. Places the file pointer at the end of the file. If files
a
does not exist then it attempts to create a file.
Opens the file for reading and writing only. Places the file pointer at the end of the
a+
file. If files does not exist then it attempts to create a file.
Once a file is opened using fopen() function it can be read with a function called fread(). This
function requires two arguments. These must be the file pointer and the length of the file
expressed in bytes.
The files's length can be found using the filesize() function which takes the file name as its
argument and returns the size of the file expressed in bytes. So here are the steps required to read
a file with PHP.
Open a file using fopen() function.
Get the file's length using filesize() function.
Read the file's content using fread() function.
Close the file with fclose() function.
The following example assigns the content of a text file to a variable then displays those contents
on the web page.
<html><head><title>Reading a file using PHP</title></head><body>
Page 2 of 13
Chapter Four Files and Directories
<?php
$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in opening file" );
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
</body></html>
Note That:- There are two ‘shortcut’ functions that don’t require a file to be opened:
$lines = file($filename) :Reads entire file into an array with each line a separate entry in
the array.
$str = file_get_contents($filename) :Reads entire file into a single string.
4.2. Writing a File
A new file can be written or text can be appended to an existing file using the PHP function as
discus in the previous discussions. These functions require two arguments specifying a file
pointer and the string of data that is to be written. Optionally a third integer argument can be
included to specify the length of the data to write. If the third argument is included, writing
would will stop after the specified length has been reached. The following is the syntax to write
files:-
fwrite(file we write on it, string what we write[,length of string])
The following example creates a new text file then writes a short text heading inside it. After
closing this file its existence is confirmed using file_exists() function which takes file name as an
argument. See the following example how open file, write in file and close files
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
Page 3 of 13
Chapter Four Files and Directories
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html><head><title>Writing a file using PHP</title></head><body>
<?php
if( file_exists( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
echo ("File $filename does not exit" );
?>
</body></html>
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file
pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function.
The fclose() function requires a file pointer as its argument and then returns true when the
closure succeeds or false if it fails.
Note that:-
The file_put_contents() function can also writes or appends a text string to a file, doesn’t
need to use fopen or fclose. If no data was written to the file, the function returns a value
of 0 which can determine if data was successfully written to the file. The FILE_APPEND
constant appends data to any existing contents in the specified filename instead of
overwriting it
Example:- This example shows costsharing payment system
<html><body>
Page 4 of 13
Chapter Four Files and Directories
<h1>Coast sharing payment system</h1>
<?php
if (isset($_GET['first_name']) && isset($_GET['last_name'])) {
$First = $_GET['first_name'];
$Last = $_GET['last_name'];
$New= $Last . ", " . "$First" . "\n";
$x = "bowlers.txt";
if (file_put_contents($x, $New, FILE_APPEND) > 0)
echo "<p>{$_GET['first_name']} {$_GET['last_name']} has been registered for the payment!</p>";
else
echo "<p>Registration error!</p>";
}
else{
echo "<p>To sign up for the cost sharing system, enter your first
and last name and click the Register button.</p>";
if(!empty($_GET['first_name']))
echo $_GET['first_name'];
if(!$_GET['last_name'])
echo $_GET['last_name'];}
?>
<form action="<?php $_PHP_SELF ?>" method="get" enctype="application/x-www-form-urlencoded">
<p>First Name: <input type="text" name="first_name" size="30" /></p>
<p>Last Name: <input type="text" name="last_name" size="30" /></p>
<p><input type="submit" value="Register" /></p>
</form></body></html >
In general;
To write files incrementally, use the fwrite() function
fclose() closes a file.
fgetc() reads a single character
feof() determines if the end is true.
fgets() reads a line of data
file() reads entire file into an array
See the following examples
Page 5 of 13
Chapter Four Files and Directories
Example 3:
<?php
Example 1:- $lines = file('welcome.txt');
foreach ($lines as $l_num => $line)
<?php
{
$myFile = "welcome.txt";
echo "Line #{$l_num}:“ .$line.”<br/>”;
if (!($fh=fopen($myFile,'r')))
}
exit("Unable to open file.");
?>
while (!feof($fh))
{ Example 4:-
$x=fgetc($fh); <?php
echo $x; $myFile = "testFile.txt";
} $fh = fopen($myFile, 'a') or die("can't open
fclose($fh); file");
?> $stringData = "New Stuff 1\n";
Example 2 fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
<?php
fwrite($fh, $stringData);
$myFile = "welcome.txt";
fclose($fh); ?>
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;?>
Locking Files
To prevent multiple users from modifying a file simultaneously use the flock() function
The syntax for the flock() function is:flock($handle, operation) where operations could
be LOCK_EX, LOCK_NB, etc. The followings are possible file lock functions and their
descriptions.
Page 6 of 13
Chapter Four Files and Directories
Reading an Entire File
Copying Files
Use the copy() function to copy a file with PHP
The function returns a value of true if it is successful or false if it is not
The syntax for the copy() function is: copy(source, destination)
For the source and destination arguments:
o Include just the name of a file to make a copy in the current directory, or
o Specify the entire path for each argument
Example:-
if (file_exists(“a.txt”)) {
if(is_dir(“history”)) {
if (copy(“a.txt”,“history\\b.txt”))
echo “<p>File copied successfully.</p>”;
else
echo “<p>Unable to copy the file!</p>”; }
else
Page 7 of 13
Chapter Four Files and Directories
echo (“<p>The directory does not exist!</p>”);}
else
echo (“<p>The file does not exist!</p>”);
4.3. Create Directories
Basic functions/methods that are used to open directories, read directories and close directories
are;-
o To iterate through the entries in a directory, open a handle to the directory with the
opendir() function
o Use the readdir() function to return the file and directory names from the open directory
o Use the closedir() function to close a directory handle
Example 1:- This is used to demonstrate how gare directory contents of files are displayed.
<?php
$Dir = "C:\\gare";
$DirOpen = opendir($Dir);
while ($CurFile = readdir($DirOpen)) {
echo $CurFile . "<br />";
closedir($DirOpen);
?>
Example 2:- The following example shows how the content of the current directory opened
$handle = opendir('./');
while(false !== ($file=readdir($handle)))
{ echo "$file<br />";
closedir($handle);
There are also different functions which have different purposes. Some of them are listed below:-
Page 8 of 13
Chapter Four Files and Directories
To create directories:-
Use the mkdir() function to create a new directory. To create a new directory pass just the name
of the directory we want to create to the mkdir() function.
Example
mkdir(“bowlers”);
mkdir(“..\\tournament”);
mkdir(“C:\\PHP\\utilities”);
Warning will appear if directory already exists
Example:-
<?php
$Dir = "C:\\Wamp";
if(is_dir($Dir)) {
echo "<table border='1‘ width='100%'>";
echo "<tr><th>Filename</th><th>File Size</th>
<th>File Type</th></tr>";
$DirEntries = scandir($Dir);
foreach ($DirEntries as $Entry) {
echo "<tr><td>$Entry</td><td>" . filesize($Dir . "\\"
. $Entry) . "</td><td>" . filetype($Dir . "\\"
. $Entry) . "</td></tr>";
}
echo "</table>";
Page 9 of 13
Chapter Four Files and Directories
}
else echo "<p>The directory does not exist.</p>";
?>
4.4. Rename and Delete Files and Directories
Use the rename() function to rename a file or directory with PHP. This function returns a
value of true if it is successful or false if it is not
o The syntax is: rename(old_name, new_name)
Use the unlink() function to delete files and the rmdir() function to delete directories
Pass the name of a file to the unlink() function and the name of a directory to the rmdir()
function. Both functions return a value of true if successful or false if not
o Use the file_exists() function to determine whether a file or directory name exists
before we attempt to delete it
4.5. Upload Files
Web applications allow visitors to upload files to and from their local computer. The files that
are uploaded and downloaded may be simple text files or more complex file types, such as
images, documents, or spreadsheets.
Files are uploaded through an HTML form using the “post” method and enctype attribute with
value of “multipart/form-data,” which instructs the browser to post multiple sections – one for
regular form data and one for the file contents. The file input field creates a browser button for
the user to navigate to the appropriate file to upload
<form method=”post” action=” ” enctype= multipart/form-data >
<input type="file" name="picture_file" />
</form>
The MAX_FILE_SIZE (uppercase) attribute of a hidden form field specifies the maximum
number of bytes allowed in the uploaded file and it must appear before the file input field.
When the form is posted, information for the uploaded file is stored in the $_FILES auto global
array.
The $_FILES[] array contains five elements:
a. // Contains the error code associated with the file $_FILES['picture_file']
['error']
b. // Contains the temporary location of the file
Page 10 of 13
Chapter Four Files and Directories
$_FILES['picture_file']['tmp_name'] contents
c. // Contains the name of the original file
$_FILES['picture_file']['name']
d. // Contains the size of the uploaded file in bytes
$_FILES['picture_file']['size']
e. // Contains the type of the file
$_FILES['picture_file']['type']
Example:-The following HTM code below creates an upload form. This form is having
method attribute set to post and enctype attribute is set to multipart/form-data
<html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=””/><br />
<input type="submit" value="Upload File" />
</form></body></html>
<?php
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
if( copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
echo "file uploded successfully";
else
die("unable to upload!");
?>
<h2>Uploaded File Info:</h2>
<ul><li>Sent file: <?php echo $_FILES['photo']['name']; ?>
<li>File size: <?php echo $_FILES['photo']['size']; ?> bytes
<li>File type: <?php echo $_FILES['photo']['type']; ?>
</ul><a href=<?php echo $target; ?>>Click here to open</a></body></html>
Example2: Inserting the above file to a database: First create a table with two columns such as
id(int auto increment) and file_path (varchar(50)).
<?php
$server="localhost";
Page 11 of 13
Chapter Four Files and Directories
$dbuser="root";
$dbpass="";
$dbname="sims";
$connection = mysql_connect($server, $dbuser, $dbpass) or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $connection) or die("Couldn't select database");
?><html><body><h3>File Upload:</h3>
Select a file to upload: <br />
<form action="<?php $_PHP_SELF ?>" method="post" enctype="multipart/form-data">
<input type="file" name="photo" required=""/><br />
<input type="submit" value="Upload File" name="upload" />
</form></body></html>
<?php
if(isset($_POST['upload']))
{
$filename=$_FILES['photo']['name'];
$filetmpname=$_FILES['photo']['tmp_name'];
$target="uploadedfiles/".$_FILES['photo']['name'];
if(!file_exists("uploadedfiles"))
mkdir("uploadedfiles");
//uploading a file into uploadedfiles folder
if(copy($_FILES['photo']['tmp_name'], $target) or die( "Could not copy file!"))
{
//inserting a file to a file table in sims database
$result = mysql_query("INSERT INTO file(file_path) VALUE ('$target')");
if(!$result)
{
echo "File uploaded successfully";
}
//retrieving records from file table
$result = mysql_query("select * from file");
echo "<table border=1><tr><th>Id</th><th>File</th></tr>";
while($row=mysql_fetch_array($result))
{
echo "<tr><th>".$row['id']."</th><th><a href='".$row['file_path']."'>".$row['file_path']."</a></th></tr>";
}
echo "</table>";
}else
Page 12 of 13
Chapter Four Files and Directories
echo "Unable to uploaded files";
}
?>
</body></html>
Page 13 of 13