ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

A beginners introduction to PHP’s file functions

(Page 3 out of 3)

Using directories

Reading a directory can be done in three different ways: using the inbuilt dir class, using the opendir() and readdir() functions or using the glob() function. The easiest way is to use the dir class, although there is very little difference.

But before you try to read a directory, you must make sure it actually is a directory and that exists, and this can be done with the is_dir() function, which checks if the directory exists, and if it is a directory. Once you've done this, you can proceed to read the directory. The below example shows you how to do this:

$dir = 'G:\projects';

// Is directory?
if (!is_dir($dir)) {
        die ('Directory doesn\'t exist');
}

// Create dir class
$d = dir($dir);

// Read directory
while (false !== ($entry = $d->read())) {
echo $entry ."";
}

// Close directory
$d->close();

?>

If you run the above code, a list of all the files and directories in the directory will be shown. The other method, using the opendir and readdir functions, is almost exactly the same:

$dir = 'G:\projects';

// Is directory?
if (!is_dir($dir)) {
        die ('Directory doesn\'t exist');
}

// Create dir class
$d = opendir($dir);

// Read directory
while (false !== ($entry = readdir())) {
echo $entry ."";
}

// Close directory
closedir($d);

?>

When reading a directory, the first two entries returned are '.' and '..'. These are not real files or directories, and usually have to be ignored, like this:

// Read directory
while (false !== ($entry = readdir())) {
        if ($entry == '.' OR $entry == '..') continue;
        echo $entry ."";
}

In the above code the '.' and '..' entries are skipped over.

The glob() function is quite different, as it returns all the filenames in an array, but glob also has another advantage: you can use wildcards to search for certain files. In the example below, we search for all PHP files in the directory:

$dir = 'G:\projects\test';

// Is directory?
if (!is_dir($dir)) {
        die ('Directory doesn\'t exist');
}

// Search for files
$files = glob($dir . '/*.php');

// List files
foreach ($files as $file) {
        echo $file . '';
}

?>

The glob function is a really easy way to get a list of files and directories, especially when you're looking for files with a certain extension or pattern. The only disadvantage is that glob is only supported by PHP 4.3 and later.

Let's have a look at creating and deleting directories. To create a new directory, you have to use the mkdir() function, which requires only two arguments: the new directory path and the permission of the directory. It's used like this:


mkdir("/path/to/my/dir", 0700);
?>

One thing to keep in mind is that the owner directory must be writable. In the example above, the /path/to/my/ directory must be writable, otherwise it's not possible to create the new directory.

It's also possible to delete directories by using the rmdir() function, which needs only one argument: the directory to delete. As with the mkdir function, the owner directory must also be writable, otherwise the directory cannot be deleted.

Conclusion

In this article I've taken you through almost every filesystem function that PHP has. There are a few more, which you can find in the PHP Manual (php.net/filesystem), but I've discussed every important one in this article.

The most important thing to remember when handling files is file permissions. Even if you're just trying to read a file, be sure to check the file permissions whether the file is readable, because it's always possible that your script can't read the file, which will likely cause errors.

If you have any comments or questions, leave a comment below, or join the PHPit Forums to talk more about PHP.

« Previous: Copying, Deleting, Properties



8 Responses to “A beginners introduction to PHP’s file functions”

  1. bhai Says:

    Yourr site is not bad .plz send me the project in php which is related to database like as any managing thing

  2. Dávur Eyðunsson Sørensen Says:

    Excellent tutorial! But since you at the end of the text boldly declare
    [quote]
    ‘I’ve discussed every important one ( meaning filesystem functions)’
    [end quote]

    I certainly would have appreciated it more if it had included at least a hint at the importance of locking your files, using flock() -http://www.php.net/flock) while reading/writing.

    Anyway, it is still a great tutorial. Keep up the good work; I read all your stuff ;)

  3. Matthijs Says:

    Nice article Dennis. Gives a good overview of the filesystem functions. The fact that you also explain when to use certain functions and when not (php versions) and why or why not to use some functions is very valuable. That’s something I often miss when I read articles. Just reading what a certain function does is what the manual is for. Reading why, how and when to use functions is what adds value. Thanks.

  4. Luke Says:

    A print view for the articles on this site would be very helpful.

  5. Bzh Says:

    I’m french and i like very much your aticles !
    It’s the second article that i read and it’s also interresting !

    On Linux platform, flock() is not useful ! flock() is importance only on a Windows platform…

    Thank you for assistance…

    Bye…

  6. mel Says:

    I found a way to make a flat file not be ever read by a website. It is pretty simple and I wanted some feedback. Mind you, I am a n00b at php. So all comments are welcome!

    here is the code:
    function acc($name, $ip, $ref, $acc_time, $store) {
    $fi = “users.php”;

    if ($store “;
    $g = fopen($fi,’a') or die (”Could not open admin file”);
    $fp = fwrite($g, $data);
    }
    if ($store > 100) {
    // delete records

    $data = “”;
    $g = fopen($fi,’w') or die (”Could not open admin file”);
    $fp = fwrite($g, $data);
    }
    }

  7. Joseph Says:

    In your second example, you have:

    $file = ‘G:\projects\phpinfo.php’;

    However, I have not been able to use PHP to load a PHP file, since, I assume, apache is trying to run the contents of $file as php code.

    How do you load a PHP file from PHP and actually be able to print the $file variable as text, which includes the without it trying to execute the PHP script.

  8. great posts Says:

    how about.. reading from a .csv file on one server, and writing to a new .csv file on another?

    Copy doesnt seem to work for me.

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Reading & Writing
  2. Copying, Deleting, Properties
  3. Using Directories
Bookmark Article
Download Article
PDF
Download this article as a PDF file