Chapter Three
Files and Directories
Outline
⚫ Write to Files
⚫ Read from Files
⚫ Create Directories
⚫ Upload Files
⚫ Rename and Delete Files and Directories
Introduction PHP Manipulating Files
⚫ PHP has several functions for creating,
reading, writing, and editing files.
⚫ When manipulating files, you must be
very careful, as mistakes can cause
significant damage.
⚫ Common errors include
⚫ Editing or deleting the wrong file.
⚫ Overwriting important data
unintentionally
Cont...
⚫ Filling the hard drive with excessive
data.
⚫ Failing to close file handles, leading to
memory leaks.
⚫ Incorrect file permissions, causing
security vulnerabilities.
⚫ Handling concurrent file access
improperly, leading to race conditions.
⚫ Not handling errors properly, resulting
in script crashes or unexpected
PHP readfile() Function
⚫ The readfile() function reads a file and writes its
contents to the output buffer.
How it works
⚫ Assume we have a text file called "webdictionary.txt" stored on
the server, containing the following content
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = HyperText Markup Language
PHP = PHP Hypertext Preprocessor
Cont…
⚫ The following PHP code reads the file and writes
its contents to the output buffer.
⚫ The readfile() function returns the number of
bytes read on success
Basic Syntax:
<?php
echo readfile("webdictionary.txt");
?>
⚫ The readfile() function is useful when you only
Cont…
Handling Errors
⚫ By default, readfile() will generate warnings if the file does not
exist. You can prevent this by using proper error handling:
<?php
$filename = "webdictionary.txt";
if (file_exists($filename))
{
echo readfile($filename);
} else {
echo "Error: File not found!";
}?>
Cont… Using readfile() for File Downloads
⚫ You can use readfile() to force a file download instead of
displaying it in the browser:
<?php
$file = "example.pdf";
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
} else {
echo "File not found."; }
?>
Cont…
Explanation:
⚫ header('Content-Disposition: attachment;
filename="..."') prompts the browser to download
the file instead of displaying it.
⚫ header('Content-Length: ...') ensures the correct
file size is sent.
⚫ exit; stops script execution after sending the file.
Cont…
Performance Considerations
⚫ readfile() is more efficient for small to medium files
because it does not require opening a file handle.
⚫ For large files, readfile() may consume too much memory.
Using fopen() and fpassthru() is a better approach:
⚫ Template-driven page generation. Including repeated
content like header/footers and navigation menus around
the “content area” of a web page.
⚫ Handling POST form input
⚫ Communication with other programs, libraries and APIs
– e.g. sending out e-mail
PHP File Open/Read/Close
⚫ PHP Open File - fopen()
⚫ A better method to open files is with the
fopen() function.
⚫ This function gives you more options than the
readfile() function.
⚫ We will use the text file, "webdictionary.txt",
during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
Cont…
⚫ The first parameter of fopen() contains the name of
the file to be opened
⚫ And the second parameter specifies in which mode
the file should be opened.
⚫ The following example also generates a message if the
fopen() function is unable to open the specified file:
⚫ Example :
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to
open file!");
Cont…
⚫ The file may be opened in one of the
following
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file
if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer
starts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already
exists
Cont….
Modes Description
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts
at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP Read File -
fread()
⚫ The fread() function reads data from an open file.
⚫ The first parameter of fread() is a file handle obtained
from fopen(), and the second parameter specifies the
maximum number of bytes to read.
⚫ The following PHP code reads the "webdictionary.txt"
file to the end:
<?php
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);
PHP Close File - fclose()
⚫ The fclose() function is used to close an open file.
⚫ Note: It's a good programming practice to close all files after you
have finished with them.
⚫ You don't want an open file running around on your server taking
up resources!
⚫ The fclose() requires the name of the file (or a variable that
holds the filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
PHP Read Single Line - fgets()
⚫ The fgets() function is used to read a single line from a
file.
⚫ The example below outputs the first line of the
"webdictionary.txt" file:
Example :
<?php
$myfile = fopen("webdictionary.txt", "r") or
die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
PHP Check End-Of-File - feof()
⚫ The feof() function checks if the "end-of-file" (EOF) has been
reached.
⚫ The feof() function is useful for looping through data of
unknown length.
⚫ The example below reads the "webdictionary.txt" file line by
line, until end-of-file is reached:
Example:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
PHP Read Single Character - fgetc()
⚫ The fgetc() function is used to read a single character from a file.
⚫ The example below reads the "webdictionary.txt" file character by
character, until end-of-file is reached:
Example :
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open
file!");
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile); ?>
⚫ Note: After a call to the fgetc() function, the file pointer moves to the
next character.
PHP File Create/Write
⚫ PHP Create File - fopen()
⚫ The fopen() function is also used to create a file. Maybe a
little confusing, but in PHP, a file is created using the
same function used to open files.
⚫ If you use fopen() on a file that does not exist, it will
create it, given that the file is opened for writing (w) or
appending (a).
⚫ The example below creates a new file called "testfile.txt".
The file will be created in the same directory where the
PHP code resides:
⚫ Example
$myfile = fopen("testfile.txt", "w")
PHP Write to File - fwrite()
⚫ The fwrite() function is used to write to a file.
⚫ The first parameter of fwrite() contains the name of the file to
write to and the second parameter is the string to be written.
⚫ The example below writes a couple of names into a new file
called "newfile.txt":
Example :
<?php
$myfile = fopen("newfile.txt", "w") or die ("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
fwrite() …Cont
⚫ Notice that we wrote to the file "newfile.txt"
twice. Each time we wrote to the file we sent the
string $txt that first contained "John Doe" and
second contained "Jane Doe". After we finished
writing, we closed the file using the fclose()
function.
⚫ If we open the "newfile.txt" file it would look
like this:
John Doe
Take away Questions
1. What are the different modes available in
fopen()?
2. What happens if you try to open a file that
does not exist using "r" mode?
3. What argument does fread() require apart
from the file pointer?
4. What is the difference between "w" and "a"
modes in fopen()?
5. What happens if you use fgets() without
checking feof()?
PHP Overwriting
⚫ Now that "newfile.txt" contains some data we can show what happens
when we open an existing file for writing. All the existing data will be
ERASED and we start with an empty file. In the example below we
open our existing file "newfile.txt", and write some new data into it:
Example :
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
⚫ If we now open the "newfile.txt" file, both John and Jane have
vanished, and only the data we just wrote is present:
Mickey Mouse
Uploading File
⚫ Create The HTML Form
⚫ Next, create an HTML form that allow users to choose the
image file they want to upload:
e.g. File.html
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post"
enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image"
name="submit">
</form>
</body>
</html>
Create The Upload File PHP Script
⚫ The "upload.php" file contains the code for uploading a
file:
<?php
$name = $_FILES ['fileToUpload']['name'];
$temp_name=$_FILES ['fileToUpload']['tmp_name'];
echo $name."<br/>";
echo $temp_name;
$location='uploads/';
?>
The move_uploaded_file() function moves an uploaded
file to a new location*/
Check if File Already Exists
⚫ Now we can add some restrictions.
⚫ First, we will check if the file already exists
in the "uploads" folder. If it does, an error
message is displayed
// Check if file already exists
if (file_exists($location.$name)) {
echo "Sorry, file already exists.";
}
Limit File Size
⚫ The file input field in our HTML form above is
named "fileToUpload".
⚫ Now, we want to check the size of the file. If the
file is larger than 500kb, an error message is
displayed:
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
}
Limit File Type
⚫ The code below only allows users to upload JPG,
JPEG, PNG, and GIF files. All other file types gives
an error message before setting:
$imageFileType=pathinfo($location.$name,PATHIN
FO_EXTENSION);
if($imageFileType != "jpg" && $imageFileType !=
"png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" )
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are
Locking a file Reading a file content
flock() function
⚫ The flock() function locks or releases a file.
⚫ This function returns TRUE on success or FALSE on failure.
Syntax
flock(file,lock,block)
⚫ Note: These locks only apply to the current PHP process.
Other processes can modify or delete a PHP-locked file if
permissions allow.
⚫ Tip: The lock is released also by fclose(), which is called
automatically when script is finished.
flock()
Parameter Description
file Required. Specifies an open file to lock or release
lock Required. Specifies what kind of lock to use. Possible values:
•LOCK_SH - Shared lock (reader). Allow other processes to access the file
•LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file
•LOCK_UN - Release a shared or exclusive lock
•LOCK_NB - Avoids blocking other processes while locking
block Optional. Set to 1 to block other processes while locking
Example
<?php
$file = fopen("test.txt","w+");
if (flock($file,LOCK_EX))
{
fwrite($file,"Write something");
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);
?>
Lab Exercises
1. Create a PHP script file write.php that writes text to a file using
w mode. Verify that the file content is written successfully.
2. Create file_read.php that reads from an existing file and
displays its content. Ensure the script properly handles errors
if the file does not exist.
3. Write a PHP script file_append.php that appends new lines to
an existing file. Verify that the new data is added without
removing previous content.
4. Use r+ mode to modify specific parts of a file without deleting
the rest. Implement logic to update only the first line of the
file.
5. Write a PHP script that opens a file in a+ mode, appends new
content, and then reads and displays the entire content.
PHP Directory
34
PHP Directory Introduction
Function Description
chdir() Changes the current directory
chroot() Changes the root directory
closedir() Closes a directory handle
dir() Returns an instance of the Directory class
getcwd() Returns the current working directory
opendir() Opens a directory handle
readdir() Returns an entry from a directory handle
rewinddir() Resets a directory handle
scandir() Returns an array of files and directories of a specified directory
35
PHP chdir() FunctionExample: ex1.php
<?php
// Get current directory
⚫ The chdir() function
echo getcwd() . "<br>";
changes the current
directory. // Change directory
Syntax chdir("c:wamp/www/file");
// Get current directory
⚫ chdir(directory,file
path); echo getcwd();
?>
C:\wamp\www\Directory
C:\wamp\www\File
36
PHP chroot() Function
Example
• The chroot() function
Change the root
changes the root directory:
directory of the current <?php
process to directory, and // Change root
changes the current
working directory to "/".
directory
chroot("/path/to/chro
• Note: This function is not
ot/");
implemented on
Windows platforms. // Get current
• Syntax directory
37 chroot(directory); echo getcwd();
PHP opendir() and closedir() Function
⚫ Open a directory, read Example:
its contents, then close: <?php
$dir =
⚫ The opendir() function
"c:wamp/www/File/uploads";
opens a directory // Open a directory, and read its
handle. contents
Syntax if (is_dir($dir)){
opendir(path); if ($dh = opendir($dir)){
while (($file = readdir($dh))
!== false){
38
echo "filename:" . $file .
"<br>";
PHP dir() Function
⚫ The dir() function returns an Example
instance of the Directory class. Use the dir() function:
<?php
⚫ This function is used to read a
$d = dir(getcwd());
directory, which includes the
echo "Handle: " . $d->handle .
following:
"<br>";
⚫ The given directory is opened
echo "Path: " . $d->path . "<br>
⚫ The two properties handle and
path of dir() are available while (($file = $d->read()) !==
⚫ Both handle and path properties false){
have three methods: read(), echo "filename: " . $file . "<br>
rewind(), and close() }
Syntax
39 $d->close();
PHP rewinddir() Function
Example
Open a directory, list its files, reset directory handle, list
its files once again, then close:
<?php
⚫ The rewinddir() $dir = "c:wamp/www/File/uploads";
// Open a directory, and read its contents
function resets the if (is_dir($dir)){
directory handle if ($dh = opendir($dir)){
// List files in uploads directory
created by while (($file = readdir($dh)) !== false){
opendir(). echo "filename:" . $file . "<br>";
}
Syntax rewinddir();
// List once again files in uploads directory
while (($file = readdir($dh)) !== false){
rewinddir(dir_handl echo "filename:" . $file . "<br>";
e); }
closedir($dh); } }
?>
40
PHP scandir() Function Result:
Array
⚫ The scandir() Example (
function returns an List files and directories
[0] => .
[1] => ..
array of files and inside the images directory: [2] => cat.gif
Ex6.php [3] =>
directories of the <?php
dog.gif
[4] =>
specified directory. $dir = " horse.gif
c:wamp/www/File/uploads "; [5] =>
Syntax // Sort in ascending order -
myimages
)
scandir(directory,sor this is default Array
$a = scandir($dir); (
ting_order,context); [0] =>
// Sort in descending order myimages
$b = scandir($dir,1); [1] =>
print_r($a); horse.gif
[2] =>
41 print_r($b); dog.gif
?>
⚫ To change permissions on directories (and
PHP chmodin()Linux,
subdirectories) Function
you can use
the chmod command with the -R (recursive)
option, along with the desired permission
settings.
⚫ It allows users to modify the read (r), write (w),
and execute (x) permissions of a file or
directory.
chmod:
⚫ This is the command-line utility used to change
file and directory permissions.
-R:
⚫ This option tells chmod to recursively apply
Common Permission Values in PHP
⚫ 0755 → Owner: rwx, Group &
Others: r-x
⚫ 0644 → Owner: rw-, Group &
Others: r--
⚫ 0777 → Everyone: rwx (⚠ Security
risk!)
777: This is a common example of a permission setting, granting read, write, and
execute permissions to everyone (owner, group, and others). my_directory:
This is the name of the directory you want to modify.
755: Owner has read, write, and execute permissions, while group and others have
read and execute permissions.
644: Owner has read and write permissions, while group and others have read-only
permissions.
a+rwx: Adds read, write, and execute permissions for all users (owner, group, and
others).
a-x: Removes execute permission for all users.
go+rX: Adds read permissions and execute permissions where appropriate for group
and others.
Permission mode in Octal
Octal Binary Permissions
0 000 No permissions
1 001 Execute only
2 010 Write only
3 011 Write & Execute
4 100 Read only
5 101 Read & Execute
6 110 Read & Write
Read, Write &
7 111
Execute
Example
⚫ Syntax <?php
$file = "example.txt";
chmod(string
$filename, int // Change permissions to 644 (Owner:
$mode): bool rw-, Group: r--, Others: r--)
if (chmod($file, 0644)) {
echo "Permissions changed
successfully!";
} else {
echo "Failed to change
permissions.";
}
?>
Takeaway questions
1. What function is used to create a new directory in PHP?
2. How can you check if a directory exists before creating it?
3. What does readdir() return when there are no more files
in a directory?
4. What does chmod("folder", 0777); do?
5. How can you skip . and .. when reading directory
contents?
6. Why can’t rmdir() delete a directory that contains files?
End of chapter 3