Interact with the Filesystem - mkdir() and rmdir()

One of the things I've found great about PHP is that it has very well supported Filesystem interactivity. Meaning, I can alter files and directories of my server very easily and with a robust nature.

While it might not be as fit as Perl, it's still well suited for a Web Development language. So, the point to this tutorial is to introduce you to two functions which as used in making and deleting directories. These functions are mkdir() and rmdir().


bool mkdir ( string pathname [, int mode [, bool recursive [, resource context]]] )

First up is mkdir(). You may have guessed that this function is used to create a directory. It accepts two parameters, the first being the directory (path can be included if your script isn't in the area where the dir is being made) and the permission of the directory.

The second parameter may be omitted in scripts being run on Windows, but, you can still include it if you like (PHP will just ignore it). However, you'll always want to set a permission on a Linux server...always =P Example time!



 <?php 
     mkdir
('/path/to/my/dir/mydirhere'0755); 
?>

As you can see the first parameter is a path. It'll create a directory named 'mydirhere' in the "dir" file which is located in the "my" dir, etc. However! Take note that mkdir() will NOT create multiple directories at once. If the directory "dir" did not exist and I ran the above script I'd get an error due to that.

The second parameter may look oddly familiar, yet not so. The last three should most definitely. This is a regular CHMOD value, but PHP suggests you keep it in Octal form. Simply add a '0' before the number =P So, '777' would be '0777'. Simple enough really.


bool rmdir ( string dirname [, resource context] )

And now for rmdir(). This does exactly the opposite of mkdir(), it'll delete a specified directory. The rules are the same as mkdir() with the first parameter. Not the second though, rmdir() doesn't require a second parameter =P Just enter the directory name (full path if need be).



 <?php 
           mkdir
('/path/to/my/dir/mydirhere'0755); 
           
rmdir('/path/to/my/dir/mydirhere'); 
?>

So the example now creates 'mydirhere' found in '/path/to/my/dir'. Sets its permission to 755. Then deletes it. I'll note again though: rmdir() will not delete multiple directors at once. The above example won't delete the 'dir', 'my', 'to', and 'path' directories, as they're the path to the last one.

And there you have it. Two very simple functions, but very useful (especially in registration scripts) ones at that. Try tinkering around with it, shouldn't take any time to get used to, they're very straight-forward. But, as with anything, the knowledge won't stay if you don't apply it =P Have fun.