PHP Echo Tutorials

Basic File Operations in PHP

Written by phpecho.com   

In this tutorial we will study some very simple but useful operations on files using PHP. In particular, we will study on how to create a directory, copy a file and write to a file. We will also cover file and directory removal.

The copy command is very straightforward to use. We will demonstrate its usage via the following example where we copy a file named 'demo.txt' from a directory called 'old' to a directory called 'new'. As part of this program, the folder 'new' would be created. The file 'demo.txt' is available in the folder 'old'.

<?php
   echo ("Example to show creation of folders and file copy in PHP <br>");
   mkdir('new/');
   echo ("The new destination folder created <br>");
   $sourceFile = "old/demo.txt";
   $destFile = "new/demo.txt";
   echo ("Going to copy file... <br>");
   copy($sourceFile, $destFile);
   echo ("File copied successfully");
   ?>


In the above example, we have created a new folder using the mkdir command. The mkdir can be used by either passing one argument or two arguments. In our example, we have supplied one argument (the folder name). The second optional argument could specify the permissions to this folder in octal mode. The two variable assignments are for creating handles to the files - both existing and new. The last non-decorative line is the copy command to copy the first file into the second.

Another very useful command for file operations is the touch syntax. The touch command is used to either set the file modification time or create a new file if it does not already exist. The syntax for this command is

touch(file, [time])

Since, we have shown how to create a new directory, we will also show how to remove a directory in this tutorial. Just like mkdir is used to create a new directory, the rmdir command can be used to remove a directory. The syntax for this PHP command is

rmdir(directory name)

The catch in the above command is that the directory can be removed only if it is empty. If it is not empty, then the files inside the directory must first be deleted and only then the directory can be removed. The files can be deleted using the unlink command whose syntax is

unlink(file)

The unlink command deletes the file whose file handler is passed.

So, in this tutorial we have covered some very basic but essential file operations using PHP. Once you have gone through this tutorial, you should be able to create and remove directories and files.