ASPit - Totally ASP
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 1 out of 3)

Introduction

Welcome to this beginner's introduction to PHP's file functions. In this article I will take you through all the inbuilt filesystem functions, and explain them. This article is mainly geared towards beginners, but it could still be useful to more advanced developers as a simple refresher.

This article will show you how to do the following things:
- reading files (using several different methods)
- writing files
- copying files
- deleting files
- getting file properties (like last modified time, last access time, etc)
- checking file permissions
- reading directories
- and more!

Let's get started with the most basic thing: reading files.

Reading Files

There are several different ways of reading a file, but before you try to read a file, you have to make sure the file exists first. To do this, PHP comes with an inbuilt function called is_readable(), which checks if the file exists and if it's readable by your script. It's possible that your script can't read the file due to permissions, even though the file does exist. It's used like this:

$file = 'G:\projects\my_file.txt';

if (is_readable($file) == false) {
        die('It doesn\'t exist or we can\'t read it!');
} else {
        echo 'It exists';
}

?>

After you've made sure that the file is readable, you can now read the file data. The easiest way to do this is with the file_get_contents() function, which requires only one argument - the file path - and immediately returns all the file data. It's used like so:

$file = 'G:\projects\phpinfo.php';

if (file_exists($file) == false) {
        die('It doesn\'t exist!');
}

// Read file
$data = file_get_contents($file);

echo htmlentities($data);

?>

The only downside with file_get_contents() is that it's only supported by PHP 4.3 and later. This means you will probably have to account for versions lower than that, which means you can't use the file_get_contents() function. The next best way is to then use the file() function, which is supported by PHP 3 and up, and is almost identical to the file_get_contents function. The only difference is that the file function returns the file data in an array, with each line as a separate item. If you just want the data as a string (like the file_get_contents function), you have to use the following code:


// Read file
$data = implode('', file($file));
?>

This method is probably the best way to read a file, and it's supported by any modern PHP version. But there is yet another way to do it, by manually opening the file, and then reading in the data. To open a file, you have to use the fopen() function, which opens a file, and returns a file resource, which can then be used with the fread() function. When opening a file, you must specify a mode in which to open the file. If all you want to do is read the file, you need to specify the 'r' mode, like in the example below:


// Read file
$f = fopen($file, 'r');
$data = fread($f, filesize($file));
fclose($f);
?>

As you can see in the above example, the fread function also needs to know how much data you want to read, which you must specify as the second argument. Since we want to read the whole file, the filesize() function is used, which returns the length of the file. When you're done with the file, you must close it with the fclose() function.

Now that I've shown you how to read a file, let's take a look at writing files.

Writing Files

Since we're now writing a file, you no longer have to check if the file exists, but you do have to check whether the file you're writing to is writable, with the is_writable() function. It's used in the same way as the is_readable function:

$file = 'G:\projects\test.txt';

if (is_writable($file) == false) {
        die('Unable to write to file');
}
?>

If the file is writeable, you can then write your data to the file. The easiest way to do this is with the file_put_contents() function which can be used to write to a file, and used like this:

$file = 'G:\projects\test.txt';

if (is_writable($file) == false) {
        die('Unable to write to file');
}

// The data
$data = 'This is my data that I\'m going to write to a file!';

// Write to file
file_put_contents ($file, $data);

?>

But the problem with the file_put_contents function is that only PHP 5 supports it, which means you can't use it if your scripts still need to support PHP 4.4 and lower. The only way to write to a file then is to use the fwrite() function, together with the fopen and fclose functions. Since we now want to write to a file, the fopen function also has to use a new mode, probably the 'w', 'a', or some other mode. See the PHP manual for the possible modes, and what they mean. The below example demonstrates the fwrite function:

$file = 'G:\projects\test.txt';

if (is_writable($file) == false) {
        die('Unable to write to file');
}

// The data
$data = 'This is my data that I\'m going to write to a file!';

// Write to file
$f = fopen($file, 'w');
fwrite($f, $data);
fclose($f);

?>

If you don't want to use the above code, and much rather use the file_put_contents function, you can add the functionality to your own scripts by creating your own file_put_contents function, like so:


// If file_put_contents() function doesn't exist, create our own
if (function_exists('file_put_contents') == false) {
        function file_put_contents($file, $string) {
           $f=fopen($file, 'w');
           fwrite($f, $string);
           fclose($f);
        }
}
?>

Let's have a look at copying and deleting files now.

Next: 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

Article Index
  1. Reading & Writing
  2. Copying, Deleting, Properties
  3. Using Directories
Download Article
PDF
Download this article as a PDF file

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.