ASPit - Totally ASP JSit - Totally JavaScript
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 2 out of 3)

Copying & Deleting Files

Deleting files is fairly easy with unlink(), but there are a few strings attached. The first thing you have to check is whether the file is writable AND if the directory is writable. If the directory that holds the file isn't writable, you won't be able to delete the file. The below example shows you how to properly delete a file:

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

// Try to delete file
$result = @unlink ($file);

// Success or failure?
if ($result == false) {
        echo 'Unable to delete file';
} else {
        echo 'File Deleted';
}

?>

Even though the above example uses the @-sign, which is generally a no-no in PHP, it's still the best way because it handles everything that we need to check for. If the directory isn't writable, the unlink function will return a failure, and the result will be false. The same happens when the file isn't writable or when the file doesn't exist. Of course you can manually check if the file and directory are writable, but why should you?

Another advantage of using the above method is that it will never cause problems when a conflict happens with another process. Imagine if another script deletes the file, while your script has just passed its checks, but hasn't run the unlink function yet. Even though all checks were true, the unlink function will still error out. That's why the above method is always the best way.

Copying files is no problem really, as PHP comes with an inbuilt copy() function which takes two arguments: the original file, and the destination file. Be aware though that the destination directory must be writable and that the original file must exist. See the example below:

$file = 'G:\projects\test.txt';
$newfile = 'G:\myfiles\newfile.txt'; # In this case G:\myfiles must be writable

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

$result = copy($file, $newfile);

if ($result == false) {
        echo 'Copying failed for some reason...';
}

?>

Now let's take a look getting some file properties, like last modified time, last access time, and a file's permissions.

Getting file properties

PHP comes with several inbuilt functions to check certain file properties, and below is a short list of all the functions:

- fileatime()
Returns the last access time of the file, as a UNIX timestamp. The last access time is changed every time data blocks of the file are read. Some filesystems have last access time disabled, although this is not common. The below example demonstrates its use:


$file = 'G:\projects\test.txt';
echo date('r', fileatime($file));
?>

- filectime()
Returns the time the file was last changed, as a UNIX timestamp. This is NOT the time the file was last changed, but the time when the metadata, like owner or file permissions, have been changed. It's used exactly like the fileatime function.

- filemtime()
Returns the time the file was last modified, as a UNIX timestamp. This is the time the file was last modified, e.g. when new data was added. It's used exactly like the fileatime function.

- fileowner()
Returns the owner of a file, which is usually the person who has created the file or uploaded it. This function actually returns the UserID of that person, which can then be resolved to a name with the posix_getpwuid() function. See the below example: (The posix_getpwuid function does NOT work on Windows)


$file = '/home/dennis/myfiles/test.txt';

$owner = posix_getpwuid(fileowner($file));

echo '

';
print_r ($owner);
echo '
'
;

?>

- fileperms()
Returns the current permissions on the file, as an integer. The below example converts the result in an octal value:


$file = 'G:\projects\test.txt';
$perms = substr(sprintf('%o', fileperms($file)), -4);
echo $perms;
?>

- filesize()
Returns the size of a file, in bytes. If you want it in a different unit, like KB or MB, you have to divide the result with 1024 for KB and 1024*1024 for MB (and 1024*1024*1024 for GB),

- stat()
Returns an array with the most common information of a file, including last access time, last modification time, and more.

That's about it for file information, and there isn't much more you can get. Let's have a look at the final part of this article: directories: reading, creating, and deleting them.

« Previous: Reading & Writing
Next: Using Directories »



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

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Reading & Writing
  2. Copying, Deleting, Properties
  3. Using Directories
Bookmark Article
Download Article
PDF
Download this article as a PDF file