0% found this document useful (0 votes)
2 views

Week 5 a Managing Files Using PHP

The document provides a comprehensive guide on file manipulation in PHP, covering operations such as checking file existence, reading and writing files, and managing file permissions. It includes examples for creating, copying, moving, deleting files, and locking mechanisms to prevent simultaneous write access. Additionally, it discusses directory handling and the use of functions like fopen, fwrite, fread, and scandir for effective file management.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Week 5 a Managing Files Using PHP

The document provides a comprehensive guide on file manipulation in PHP, covering operations such as checking file existence, reading and writing files, and managing file permissions. It includes examples for creating, copying, moving, deleting files, and locking mechanisms to prevent simultaneous write access. Additionally, it discusses directory handling and the use of functions like fopen, fwrite, fread, and scandir for effective file management.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Using Files in PHP

We shall consider the followings:


 Checking Whether a File Exists.
 Read and write files, and check file permissions
 Obtain and parse a directory listing in PHP.
Powerful as it is, MySQL is not the only (or necessarily the
best) way to store all data on a web server. Sometimes it can
be quicker and more convenient to directly access files on the
hard disk. Cases in which you might need to do this are
modifying images, or log files that you wish to process. PHP
comes with a powerful and flexible file manipulation API,
which enables developers to view and modify file attributes,
read and list directory contents, alter file permissions, retrieve
file contents into a variety of native data structures, and
search for files based on specific patterns.
Note: Always assume that the system you are working on(Linux or
UNIX) is case-sensitive and stick to a convention such as all
lowercase filenames. Since Windows and Mac OS X filenames are
not case-sensitive, but Linux and Unix ones are.
Checking Whether a File Exists
Handling File

To determine whether a file already exists, you can use the


file_exists function, which returns either TRUE or FALSE, and is
used like this:
Syntax: if (file_exists("testfile.txt")) echo "File exists";

Creating a file
At this point we assume testfile.txt doesn’t exist, so let’s
create it and write a few lines to it
Example:
<?php // testfile.php
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
_END;
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);
echo "File 'testfile.txt' written successfully";
?>
Writing string into a File
To write a string to a file, we can use file_put_contents() function

Example:
<?php
// define string to write
$data = "All the world's a stage\r\nAnd all the men and women
merely players";
// write string to file
file_put_contents(‘file11.txt', $data) or die("Cannot write to file");
echo "File successfully written.";
?>
Note:
The file_put_contents() function provides an easy way to write
data to a file.
The file will be created if it does not already exist, and
overwritten if it does. The
return value of the function is the number of bytes written.
File Sequence Handling
1. Always start by opening the file. This is done through a call to fopen.
2. Then you can call other functions; here we write to the file (fwrite), but you
can also read from an existing file (fread or fgets) and do other things.
3. Finish by closing the file (fclose). Although the program does this for you
when it ends, you should clean up yourself by closing the file when you’re
finished.
Different types of parameters mode
Mode Action Description
'r' Read from file start Open for reading only; place the file pointer at the beginning of the file. Return
FALSE if the file doesn’t already exist.
'r+‘ Read from file start and allow
writing Open for reading and writing; place the file pointer at the beginning of the file.
Return FALSE if the file doesn’t already exist.
'w' Write from file start and truncate file
Open for writing only; place the file pointer at the beginning of the file and
truncate the file to zero length. If the file doesn’t exist, attempt to create it.
'w+' Write from file start, truncate
file and allow reading Open for reading and writing; place the file pointer at the beginning of the file
and truncate the file to zero length. If the file doesn’t exist, attempt to create it.
'a‘ Append to file end Open for writing only; place the file pointer at the end of the file. If
the file doesn’t exist, attempt to create it.
'a+' Append to file end and allow
reading Open for reading and writing; place the file pointer at
the end of the file. If the file doesn’t exist, attempt to
create it.
Reading from Files
The easiest way to read from a text file is to grab a whole line through fgets
(think of the final s
as standing for “string”)
Example: Reading a file with fgets
<?php
$fh = fopen("testfile.txt", 'r') or
die("File does not exist or you lack permission to open it");
$line = fgets($fh);
fclose($fh);
echo $line;
?>

Example:Reading a file with fread


<?php
$fh = fopen("testfile.txt", 'r') or
die("File does not exist or you lack permission to open it");
$text = fread($fh, 3);
fclose($fh);
echo $text;
?>
Note:The fread function is commonly used with binary data. But if you use
it on text data
that spans more than one line, remember to count newline characters.
Copying Files
We can use PHP copy function to create a clone of testfile.txt.
Example: Copying a file
<?php // copyfile.php
copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
echo "File successfully copied to 'testfile2.txt'";
?>

Example: Alternate syntax for copying a file


<?php // copyfile2.php
if (!copy('testfile.txt', 'testfile2.txt')) echo "Could not copy file";
else echo "File successfully copied to 'testfile2.txt'";
?>

Moving a File
To move a file, rename it with the rename function.
Example:
<?php // movefile.php
if (!rename('testfile2.txt', 'testfile2.new'))
echo "Could not rename file";
else echo "File successfully renamed to 'testfile2.new'";
?>
Note:You can use the rename function on directories, too. To avoid any
warning messages,
if the original file doesn’t exist, you can call the file_exists function first to
check.
Deleting a File

Deleting a file is just a matter of using the unlink function to


remove it from the file system.
Example:
<?php // deletefile.php
if (!unlink('testfile2.new')) echo "Could not delete file";
else echo "File 'testfile2.new' successfully deleted";
?>

Locking and Unlocking Files


To lock a file before writing to it use the flock() function
Example:
<?php
// open file
$fp = fopen('dummy.txt', "wb+") or die ("Cannot open file");
// lock file
// write string to file
if (flock($fp, LOCK_EX)) {
fwrite($fp, "This is a test.") or die("Cannot write to file");
flock($fp, LOCK_UN);
} else {
die ("Cannot lock file");
}
// close file
fclose($fp) or die ("Cannot close file");
echo "File successfully written.";
?>
PHP implements both shared and exclusive file locks through its flock()
function, which
accepts a file pointer and a flag indicating the lock type (LOCK_EX for
exclusive lock,
LOCK_SH for shared lock, and LOCK_UN for unlock).
Once a file is locked with flock(), other processes attempting to write
to the file have
to wait until the lock is released; this reduces the possibility of multiple
processes
trying to write to the same file simultaneously and corrupting it.
Note:
Processing Directories
Users of older
To iteratively Windows
process all versions
the filesare particularly
in a directoryprone to the problem,
use PHP’s
as flock()
scandir() does
function
not work with the FAT file system
Example:
<?php
// define directory path
$dir = './test';
// get directory contents as an array
$fileList = scandir($dir) or die ("Not a directory");
// print file names and sizes
foreach ($fileList as $file) {
if (is_file("$dir/$file") && $file != '.' && $file != '..') {
echo "$file: " . filesize("$dir/$file") . "\n";
}
}
scandir() function returns the contents of a directory as an array,
which can then be
processed using any loop construct or array function.
Renaming Files and Directories
To move or rename a file or directory we use PHP’s rename()
function
Example:
<?php
// set old and new file/directory names
$oldFile = "home/john";
$newFile = "home/jane";
// check if file/directory exists
// if it does, move/rename it
if (file_exists($oldFile)) {
rename ($oldFile, $newFile) or die("Cannot move/rename file '$oldFile'");
echo "Files/directories successfully renamed.";
} else {
die ("Cannot find file '$oldFile'");
}
?>

You might also like