Working With PHP Files and Directories Part-2

PHP Files and Folders

Processing Directories

PHP also allows developers to work with directories on the file system, iterating through directory contents or moving forward and backward through directory trees. Iterating through a directory is a simple matter of calling PHP’s DirectoryIterator object, as in the following example, which uses the DirectoryIterator to read a directory and list each file within it:


<?php

// initialize iterator with name of

// directory to process

$dit = new DirectoryIterator('.');

// loop over directory

// print names of files found

while($dit->valid()) {

if (!$dit->isDot()) {

echo $dit->getFilename() . "\n";

}

$dit->next();

}

unset($dit);

?>

Here, a DirectoryIterator object is initialized with a directory name, and the object’s rewind() method is used to reset the internal pointer to the first entry in the directory. A while loop, which runs so long as a valid() entry exists, can then be used to iterate over the directory. Individual filenames are retrieved with the getFilename() method, while the isDot() method can be used to filter out the entries for the current (.) and parent (..) directories. The next() method moves the internal pointer forward to the next entry.

You can also accomplish the same task with a while loop and some of PHP’s directory manipulation functions . . . as in the following listing:


<?php

// create directory pointer

$dp = opendir('.') or die ('ERROR: Cannot open directory');

// read directory contents

// print filenames found

while ($file = readdir($dp)) {

if ($file != '.' && $file != '..') {

echo "$file \n";

}

}

// destroy directory pointer

closedir($dp);

?>

Here, the opendir() function returns a pointer to the directory named in the function call. This pointer is then used by the readdir() function to iterate over the directory, returning a single entry each time it is invoked. It’s then easy to filter out the . and .. directories, and print the names of the remaining entries. Once done, the closedir() function closes the file pointer.

TIP

Also consider PHP’s scandir() function, which accepts a directory name and returns an array containing a list of the files within that directory together with their sizes. It’s then easy to process this array with a foreach loop.

In some cases, you might need to process not just the first-level directory, but also its subdirectories and sub-subdirectories. A recursive function, which you learned about in Chapter 5, is usually the best tool for this purpose: consider the next listing, which illustrates one such function in action:


<?php

// function definition

// print names of files in a directory

// and its child directories

function printDir($dir, $depthStr='+') {

if (file_exists($dir)) {

// create directory pointer

$dp = opendir($dir) or die ('ERROR: Cannot open directory');

// read directory contents

// print names of files found

// call itself recursively if directories found

while ($file = readdir($dp)) {

if ($file != '.' && $file != '..') {

echo "$depthStr $dir/$file \n";

if (is_dir("$dir/$file")) {

printDir("$dir/$file", $depthStr.'+');

}

}

}

// close directory pointer

closedir($dp);

}

}

// print contents of directory

// and all children

if (file_exists('.')) {

echo '<pre>';

printDir('.');

echo '<pre>';

}

?>

The printDir() function in this listing might appear complex, but it’s actually quite simple. It accepts two arguments: the name of the top-level directory to use, and a “depth string,” which indicates, via indentation, the position of a particular file or directory in the hierarchy. Using this input, the function opens a pointer to the named directory and begins processing it with readdir(), printing the name of each directory or file found. In the event that a directory is found, the depth string is incremented by an additional character and the printDir() function is itself recursively called to process that subdirectory. This process continues until no further files or directories remain to be processed.

Figure 3 has an example of the output of this listing.

Show files and Directory List Using PHP

Performing Other File and Directory Operations

In addition to the tools you’ve seen in previous sections, PHP comes with a whole range of file and directory manipulation functions, which allow you to check file attributes;

copy, move, and delete files; and work with file paths and extensions. Table 6-1 lists some of the important functions in this category.

Checking if a File or Directory Exists

If you try reading or appending to a file that doesn’t exist, PHP will typically generate a fatal error. Ditto for attempts to access or read/write from/to a directory that doesn’t exist. To avoid these error messages, always check that the file or directory you’re attempting to access already exists, with PHP’s file_exists() function. The next listing illustrates it in action:

Function

What It Does

file_exists()

Tests if a file or directory exists

filesize()

Returns the size of a file in bytes

realpath()

Returns the absolute path of a file

pathinfo()

Returns an array of information about a file and its path

stat()

Provides information on file attributes and permissions

is_readable()

Tests if a file is readable

is_writable()

Tests if a file is writable

is_executable()

Tests if a file is executable

is_dir()

Tests if a directory entry is a directory

is_file()

Tests if a directory entry is a file

copy()

Copies a file

rename()

Renames a file

unlink()

Deletes a file

mkdir()

Creates a new directory

rmdir()

Removes a directory

include() / require()

Reads an external file into the current PHP script

Table: Common PHP File and Directory Functions


<?php

// check file

if (file_exists('somefile.txt')) {

$str = file_get_contents('somefile.txt');

} else {

echo 'Named file does not exist. ';

}

// check directory

if (file_exists('somedir')) {

$files = scandir('somedir');

} else {

echo 'Named directory does not exist.';

}

?>

Calculating File Size

To calculate the size of a file in bytes, call the filesize() function with the filename as argument:


<?php

// get file size

// output: 'File is 1327 bytes.'

if (file_exists('example.txt')) {

echo 'File is ' . filesize('example.txt') . ' bytes.';

} else {

echo 'Named file does not exist. ';

}

?>

Finding the Absolute File Path

To retrieve the absolute file system path to a file, use the realpath() function, as in the next listing:


<?php

// get file path

// output: 'File path: /usr/local/apache/htdocs/

//          /php-book/ch06/listings/example.txt'

if (file_exists('example.txt')) {

echo 'File path: ' . realpath('example.txt');

} else {

echo 'Named file does not exist. ';

}

?>

You can also use the pathinfo() function, which returns an array containing the file’s path, name, and extension. Here’s an example:



<?php

// get file path info as array

if (file_exists('example.txt')) {

print_r(pathinfo('example.txt'));

} else {

echo 'Named file does not exist. ';

}

?>

Retrieving File Attributes

You can obtain detailed information on a particular file, including its ownership, permissions, and modification and access times, with PHP’s stat() function, which returns this information as an associative array. Here’s an example:


<?php

// get file information

if (file_exists('example.txt')) {

print_r(stat('example.txt'));

} else {

echo 'Named file does not exist. ';

}

?>

You can check if a file is readable, writable or executable with the is_readable(), is_writable(), and is_executable() functions. The following example illustrates their usage:


<?php

// get file information

// output: 'File is: readable  writable'

if (file_exists('example.txt')) {

echo 'File is: ';

// check for readable bit

if (is_readable('example.txt')) {

echo ' readable ';

}

// check for writable bit

if (is_writable('example.txt')) {

echo ' writable ';

}

// check for executable bit

if (is_executable('example.txt')) {

echo ' executable ';

}

} else {

echo 'Named file does not exist. ';

}

?>

The is_dir() function returns true if the argument passed to it is a directory, while the is_file() function returns true if the argument passed to it is a file. Here’s an example:


<?php

// test if file or directory

if (file_exists('example.txt')) {

if (is_file('example.txt')) {

echo 'It\'s a file.';

}

if (is_dir('example.txt')) {

echo 'It\'s a directory.';

}

} else {

echo 'ERROR: File does not exist.';

}

?>

Creating Directories

To create a new, empty directory, call the mkdir() function with the path and name of the directory to be created:


<?php

if (!file_exists('mydir')) {

if (mkdir('mydir')) {

echo 'Directory successfully created.';

} else {

echo 'ERROR: Directory could not be created.';

}

} else {

echo 'ERROR: Directory already exists.';

}

?>

Copying Files

You can copy a file from one location to another by calling PHP’s copy() function with the file’s source and destination paths as arguments. Here’s an example:


<?php

// copy file

if (file_exists('example.txt')) {

if (copy('example.txt', 'example.new.txt')) {

echo 'File successfully copied.';

} else {

echo 'ERROR: File could not be copied.';

}

} else {

echo 'ERROR: File does not exist.';

}

?>

It’s important to note that if the destination file already exists, the copy() function will overwrite it.

Renaming Files or Directories

To rename a file (or directory), call PHP’s rename() function with the old and new path names as arguments. Here’s an example that renames a file and a directory, moving the file to a different location in the process:


<?php

// rename/move file

if (file_exists('example2.txt')) {

if (rename('example2.txt', '../example.new.txt')) {

echo 'File successfully renamed.';

} else {

echo 'ERROR: File could not be renamed.';

}

} else {

echo 'ERROR: File does not exist.';

}

?>

See Another Example


<?php

// rename directory

if (file_exists('mydir')) {

if (rename('mydir', 'myotherdir')) {

echo 'Directory successfully renamed.';

} else {

echo 'ERROR: Directory could not be renamed.';

}

} else {

echo 'ERROR: Directory does not exist.';

}

?>

As with copy(), if the destination file already exists, the rename() function will overwrite it.

CAUTION

PHP will only allow you to copy, delete, rename, create, and otherwise manipulate a file or directory if the user “owning” the PHP script has the privileges necessary to perform the task.

Removing Files or Directories

To remove a file, pass the filename and path to PHP’s unlink() function, as in the following example:


<?php

// delete file

if (file_exists('dummy.txt')) {

if (unlink('dummy.txt')) {

echo 'File successfully removed.';

} else {

echo 'ERROR: File could not be removed.';

}

} else {

echo 'ERROR: File does not exist.';

}

?>

To remove an empty directory, PHP offers the rmdir() function, which does the reverse of the mkdir() function. If the directory isn’t empty, though, it’s necessary to first remove all its contents (including all subdirectories) and only then call the rmdir() function to remove the directory. You can do this manually, but a recursive function is usually more efficient—here’s an example, which demonstrates how to remove a directory and all its children:


<?php

// function definition

// remove all files in a directory

function removeDir($dir) {

if (file_exists($dir)) {

// create directory pointer

$dp = opendir($dir) or die ('ERROR: Cannot open directory');

// read directory contents

// delete files found

// call itself recursively if directories found

while ($file = readdir($dp)) {

if ($file != '.' && $file != '..') {

if (is_file("$dir/$file")) {

unlink("$dir/$file");

} else if (is_dir("$dir/$file")) {

removeDir("$dir/$file");

}

}

}

// close directory pointer

// remove now-empty directory

closedir($dp);

if (rmdir($dir)) {

return true;

} else {

return false;

}

}

}

// delete directory and all children

if (file_exists('mydir')) {

if (removeDir('mydir')) {

echo 'Directory successfully removed.';

} else {

echo 'ERROR: Directory could not be removed.';

}

} else {

echo 'ERROR: Directory does not exist.';

}

?>

Here, the removeDir() function is a recursive function that accepts one input argument: the name of the top-level directory to remove. The function begins by creating a pointer to the directory with opendir() and then iterating over the directory’s contents with a while loop—you’ve seen this technique in a previous section of this chapter. For each directory entry found, the is_file() and is_dir() methods are used to determine if the entry is a file or a sub-directory; if the former, the unlink() function is used to delete the file and if the latter, the removeDir() function is called recursively to again process the subdirectory’s contents. This process continues until no files or subdirectories are left; at this point, the top-level directory is empty and can be removed with a quick rmdir().

Replace a string from an associative array

We have a list of string to be replaced within a file.


<?php

$file_name = 'test1.txt';

$str_replace = array('Father'=>'Mother','love'=>'care');

// open file for reading only

$file_handler_1 = fopen($file_name, 'r') or exit('can not open file!');

// store the file content into $file_content_1

$file_content_1 = fread($file_handler_1, filesize($file_name));

// replace file content with a list of string

$new_file_content =

str_replace(array_keys($str_replace), array_values($str_replace), $file_content_1);

// close file

fclose($file_handler_1);

$file_handler_2 = fopen($file_name, 'w+') or exit('can not open file!');

if (fwrite($file_handler_2, $new_file_content)) {

echo 'successfully write to the file<br/>';

} else {

echo 'can not write to the file<br/>';

}

fclose($file_handler_2);

?>

URL Content

Get URL content

<?php

$file = fopen('http://jobs.perl.org/','r');

$count_line=0;
while (!feof($file)) {
echo $count_line.' '. htmlspecialchars(fgets($file)) . "<br/>";
$count_line++;
}
fclose($file);

?>

Email Template

myprofile.txt

[txt]

Hi [[:friend]],

How are you [[:friend]]? Today is [[:today]], I will go to shopping mall to buy some clothes.
Do you want to go with me? There are many friend will go with us? Do you know [[:ourfriend]]?

I am looking forward to hear from you? My number is [[:phonenumber]]. We are ging to meet at [[:place]]. 

See you,

[[:myname]] 
[/txt]

Email Template

We want to create a text file template for our email.

myLetter.php

<?php

$file_name = 'myprofile.txt';

$array_email = array('[[:myname]]'=>'John',
'[[:friend]]'=>'Cristina',
'[[:today]]'=>'Sunday',
'[[:ourfriend]]'=>'Janny',
'[[:phonenumber]]'=>'318-555-3333',
'[[:place]]'=>'Dillair Mall');
// open file for reading only

$file_content_1 = file_get_contents($file_name);
// replace file content
$new_file_content = str_replace(array_keys($array_email), array_values($array_email), $file_content_1);

echo '<pre>'.$new_file_content . '</pre>';

?>

Display
Hi Cristina,

How are you Cristina? Today is Sunday, I will go to shopping mall to buy some clothes.
Do you want to go with me? There are many friend will go with us? Do you know Janny?

I am looking forward to hear from you? My number is 318-555-3333. We are ging to meet at Dillair Mall.

See you,

John

Text File Template
book.txt

The book Infor:
Author: {:author}
Price: {:price}
Publisher: {:publisher}
Title: {:title}
Info: {:body}

bookTemplate.php

<?php
$file = 'book.txt';

$template_aa = array('{:author}','{:price}','{:publisher}','{:title}','{:body}');
$array_aa = array('Jannifer Bill',30,'Orailly','PHP/MySQL','It\' a book for Web Developer and MySQL');

if (file_exists($file)) {
 $file_content = file_get_contents($file);
 $fin_content = str_replace($template_aa, $array_aa, $file_content);
 print nl2br($fin_content);
}
?>

Display
The book Infor:
Author: Jannifer Bill
Price: 30
Publisher: Orailly
Title: PHP/MySQL
Info: It’ a book for Web Developer and MySQL


Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.
5 comments on “Working With PHP Files and Directories Part-2
  1. I have been examinating out some of your articles and i must say nice stuff. I will make sure to bookmark your blog.

  2. Very good written story. It will be beneficial to anyone who utilizes it, as well as me. Keep up the good work looking forward to more posts.

Leave a Reply

Your email address will not be published. Required fields are marked *