Zend PHP 7 Certification – Input/Output – Filesystem Functions

This post covers the Filesystem Functions section of the Input/Output chapter when studying for the Zend PHP 7 Certification.

PHP provides a number of filesystem functions that help read and write file data. Some of those functions can be seen and described in more details below.

The fopen() function opens a file or a URL. It takes two parameters.

  • Filename – the filename itself as a string
  • Mode

The modes that can be used with the function can be seen below.

  • r – Open for reading only; place the file pointer at the beginning of the file.
  • r+ – Open for reading and writing; place the file pointer at the beginning of the file.
  • w – Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • w+ – Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
$handle = fopen("/home/user/file.txt", "r");
$handle = fopen("/home/user/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");

It should be noted that using fopen() in w mode will not update the modification time of a file like you may expect.

The fwrite() function writes the contents of string to the file stream pointed to by handle. Note that the file() function reads the contents into an array.

$handle = fopen("/home/user/file.txt", "w+");
fwrite($handle, "some text");

If a third length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

The fclose() function closes an open file pointer. It’s good practice to close all files after you have finished with them.


$handle = fopen('somefile.txt', 'r');


The file_get_contents() function reads an entire file into a string. It can take up to 5 parameters.

  • Filename – The name of the file
  • Use include path – The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search.
  • Context – A valid context resource
  • Offset – The offset where the reading will start
  • Maxlength – Maximum length of data read.
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;

To read certain sections of files, pass in the offset as the fourth parameter starting from 0. Use NULL for the second and third parameters if you do not wish to change them.

// Read 14 characters starting from the 21st character
$section = file_get_contents('people.txt', NULL, NULL, 20, 14);

The file_get_contents() function is similar to file() function, except that file_get_contents() returns the contents as a string and returns false on failure. file() reads an entire file into an array.

As oh PHP version 7.1, support for negative offsets has been added for this function

The file_put_contents() function writes a string to a file.

Identically to calling fopen(), fwrite() and fclose() successively to write data to a file. If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set. There are three parameters that are used in the function.

  • Filename – The file name
  • Data – The contents of the file to add to the file
  • Flag – Flags such as FILE_APPEND append the data to the file rather than overwriting it.
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);

The chmod() function attempts to change the mode of the specified file to that given in mode.

chmod("/somedir/somefile", 0755);  // octal; correct value of mode

The chown() function attempts to change the owner of the file filename to user user.

// Set the user
chown($path, $user_name);

The copy() function copies a file.

$file = 'example.txt';
$newfile = 'example.txt.bak';

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

The dirname() function returns a parent directory’s path.

echo dirname("/some/directory/file.php"); // Outputs: /some/directory

Note that you can also use the __DIR__ constant to achieve the same result.

The feof() function tests for end-of-file on a file pointer.

$fp = fopen('test.html','r');
if ($fp) {
    while(!feof($fp)) {
        // Do something

The file_exists() function checks whether a file or directory exists.

$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";

The glob() function searches for all the pathnames matching pattern and returns an array.

foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";

The is_writable() function returns TRUE if the filename exists and is writable.

$filename = 'test.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';

The pathinfo() function returns information about path: either an associative array or a string, depending on options.

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0

The rewind() function sets the file position indicator for handle to the beginning of the file stream.

$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
fwrite($handle, 'Foo');

echo fread($handle, filesize('output.txt'));


// Outputs:
Foolly long sentence

The unlink() function deletes a file.

$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');


The umask() function sets PHP’s umask to mask & 0777 and returns the old umask.

$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);

// Checking
if ($old != umask()) {
    die('An error occurred while changing back the umask');

Note: This article is based on PHP version 7.1.