File System Management

PHP gives you an awesome bargain of tools for opening, creating, uploading, and editing files. At the time you are controlling files, you must be extremely watchful on the grounds that you can do a considerable measure of harm if something happens.

Regular errors include editing the wrong file, filling a hard-drive with garbage data, and incidentally erasing a file’s content.

Normal errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file’s content.

Lesson Goals

  • Read from files on the server.
  • Write to files on the server.
  • File locking.
  • Deleting Files and Directories.
  • Copying Files to Directories

Opening a File

The PHP fopen () function is used to open a file. It requires two arguments, stating first the file name and then the mode in which to operate.

The PHP fopen () function takes two parameters,

  1. file name (should provide a correct path) and
  1. the mode in which the file should be opened.

The function returns a file pointer if successful, otherwise zero (false). Files are opened with the PHP fopen () function for reading or writing.

The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:

$myFile = @fopen('MyFile.txt','a');
if (!$myFile)
{
    echo 'Sorry, but the file cannot be opened.';
}
else
{
    // code for processing file
}

Files that do not have the appropriate permission settings will fail to open. In this case, the fopen () function will return false and a warning will be given. Use conditional processing as shown below to handle this situation.

The @ symbol in front of the first line of code is used to suppress errors. Any errors can then be handled more gracefully.

Files modes can be specified as one of the six options in this table.

ModeDescription
rRead only. Opens the file for reading only.
Places the file pointer at the beginning of the file.
r+Read/Write.Opens the file for reading and writing.
Places the file pointer at the beginning of the file.
w

Write only.It opens the file for writing only.

It places the file pointer at the beginning of the file.

and truncates the file to zero length. If files do not

If it exists, then it attempts to create a file.

w+

Read/Write.It opens the file for reading and writing only.

It places the file pointer at the beginning of the file.

and truncates the file to zero length. If files do not

If it exists, then it attempts to create a file.

a

Append.It opens the file for writing only.

It places the file pointer at the end of the file.

If files do not exist, then it attempts to create a file.

a+

Read/Append.It opens the file for reading and writing only.

It places the file pointer at the end of the file.

If files do not exist, then it attempts to create a file.

xWrite only.Creates a new file. Returns FALSE and an error if file already exists
x+Read/Write.Creates a new file. Returns FALSE and an error if file already exists

If an attempt to open a file fails, then fopen returns a value of false, otherwise it returns a file pointer which is used for further reading or writing to that file.

After making changes to the opened file, it is important to close it with the fclose () function. The fclose () function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.

Note: If the fopen () function is unable to open the specified file, it returns 0 (false).

Read Files With PHP

There are two useful methods for reading files with PHP that will be covered in this PHP Tutorial. The first method is using the fread function. This method requires a combination of the functions: fopenfread, and fclose functions. The file_get_contents function is used in the second method that will be covered – it eliminates the need to call multiple functions to read a file in PHP.

When using both of the methods covered in this PHP Tutorial, the file will be read to a string – this can be saved in a variable for later use. Reading files into variables is not always necessary. Sometimes you can use the returned data from the file directly.

The files’s length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.

So here are the steps required to read a file with PHP.

  • Open a file using fopen() function.
  • Get the file’s length using filesize() function.
  • Read the file’s content using fread() function.
  • Close the file with fclose() function.

The following example assigns the content of a text file to a variable then displays those contents on the web page.

fgets()

fgets() is used to read a file one line at a time. It requires one argument: the resource or “handle” for the file, and accepts a second argument: the length of the line. It will continue reading the line until the length-1 has been read or it reaches the end of the line or the end of the file. If the second argument is not included, it will continue reading until it reaches the end of the line.

$filename = "/home/user/guest/tmp.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
   echo ( "Error in opening file" );
   exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );

fclose( $file );

echo $filesize;
echo $filetext";

As was mentioned earlier, the fread function uses a combination of: fopen, fread, and fclose. The file is first opened for reading using fopen with the r mode – this mode will open the file for reading, and place the pointer at the beginning of the file.

The second argument in the fread function, which is the staple for getting data out of a file. The function requires a file handle, which we have, and an integer to tell the function how much data, in bytes, it is supposed to read.

One character is equal to one byte. If you wanted to read the first five characters, then you would use five as the integer.

Other options for reading from files
FunctionDescription
fgetss()Like fgets() but it strips out HTML and PHP tags.
fgetcsv()Like fgets() but it splits the file on a specified delimiter rather than a newline character.
readfile()Opens a file, sends its contents to the browser, and closes the file.
file()Opens a file, splits it into an array on newline characters, and closes the file.

Writing to a File

Opening a file for writing involves three steps:

  1. Open the file.
  2. Write to the file.
  3. Close the file.

Syntax

fwrite(file_pointer,output_string)

The output_string is the text to write to the file. See the following example of writing to a file.

$outputString='text to write';
$myFile = @fopen('Employees.txt', 'a');
fwrite($myFile, $outputString);
fclose($myFile);

File Locking

flock()

flock() is used to lock a file so that two or more people do not get access to it at the same time. This helps protect the file from being corrupted. flock() takes two arguments: a file handler and a lock type. flock() does not work with NFS or other networked file systems or with such as FAT that does not support file locking.

Lock TypeExplanation
LOCK_SHReading lock. Others can read file.
LOCK_EXExclusive lock. The file cannot be opened by others.
LOCK_UNUnlocks file.
LOCK_NBIf a file is already locked by another user, flock() waits to get a lock. LOCK_NB tells it not to wait.

The code below shows how we should change Files/Solutions/AddEntry.php to protect Employees.txt from being corrupted.

Deleting Files and Directories With PHP

Deleting files with PHP can be done with the unlink function. If you want to delete the entire contents of a directory, you may want to include the files in an array, then cycle through this array with a loop, and delete the files one by one.

One of the main reasons for deleting files is to free up storage space. Deleting the entire contents of a directory is often done to make it possible to use rmdir to remove the directory itself.

Deleting a file is really simple. All you need to do is to write the path to the file that you want to delete. An example of how to delete a.html file is shown below:

unlink('my-html-file.html');

This only shows how to delete a single file, so let’s show how to delete the entire contents of a given directory.

Delete the contents of a directory

To delete the contents of a directory with php, you can use the glob function to return the contents as an array, then cycle trough this array to delete files one by one.

$aFiles = glob("Cookies/*.txt");

$n = count($aFiles);
$counter = 0;
while ($counter < $n) {
  unlink($aFiles["$counter"]);
  ++$counter;
}

You can also use a foreach loop to cycle trough the results directly, the below would delete the directory contents of “MyDirectory” one by one.

$dir = 'MyDirectory/';
  foreach(glob($dir.'*.*') as $item){
    unlink($item);
}

Deleting the directory contents is needed before you can delete the directory itself, which is done with the rmdir function, this is demonstrated in the below example:

rmdir('MyDirectory');

Copying files in PHP

Copying files can be done with the copy function of PHP. This function will also accept URLs in the source parameter, given that the fopen wrappers have been enabled.

Copying files is really simple. The below example shows how to copy a text file, renaming it in the process. Keep in mind that the destination file will be overwritten if it already exists, so it can be a good idea to rename the file if you don’t want that to happen.

$file = 'MyTextFile.txt';
$newfile = 'MyTextFile-copy.txt';

if (!copy($file, $newfile)) {
    echo "failed to copy $file.";
}

The above consists of two variables and a single if statement. The if statement will check if the file copy failed. The copying is happening inside the if-check, so do not be confused about this. It simply runs the function, and then checks the return value.

Copying Files to Directories

When copying a file to another directory, you should first create the directory before it will be possible to copy files to it. If the directory already exists, just do something like:

$source = 'MyTextFile.txt';
$destination = 'mydir/MyTextFile-copy.txt';

if (!copy($source, $destination)) {
    echo "failed to copy: $source";
}

Copying remote files

Remote files are located on other servers, copying them will mean that you have to download them. The copy function can also be used on remote files, given that the fopen wrappers are enabled.

The below example demonstrates how to use copy to download remote files. Note. You won’t be able to download the source-code of remote PHP scripts!

 if(!copy('http://example.com/myfile.txt','mydir/FileName.txt')) {
    $errors = error_get_last();
    echo $errors['type'];
    echo $errors['message'];
  }

Renaming Files with PHP

Renaming files is done with the rename function of PHP. This function not only allows you to rename files, it can also be used to move files in the renaming process. The function rename takes just 2 parameters that we care about. The first is the oldname and the second is the newname, representing the current location and file name, and the new one respectively.

  rename("/MyDIR/MyFileName.txt", "/AnotherDir/my-new-file-name.txt");

The rename function also works on URLs if the URL wrappers has been enabled, you can read more about that in the tutorials on HTTP requests.

File Renaming in PHP

Renaming files has never been easier. To rename a file that lives in a directory – without moving it to another directory – you should do like demonstrated in the below example:

 rename("/folder/old-file-name.ext", "/folder/new-file-name.ext");

Keep in mind that the rename function operates from the PHP Working Directory, as such the above examples are using root relative paths to access, rename and/or move files.

To easily find out what the current working directory is, you may want to do something like below:

 echo getcwd() . "
";

chdir('MySubDir');

// New directory after Changing using chdir to change directory!
echo getcwd() . "
";

Add a Comment

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

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com