Before you read or change a file, check that it is there and that you may use it.
Does it exist?
<?php
file_put_contents("data.txt", "x");
var_dump(file_exists("data.txt"));
var_dump(file_exists("nothing.txt"));
bool(true)
bool(false)
file_exists() is true for files and folders. To be precise, use these:
| Function | True when |
|---|---|
is_file($p) | It is a regular file |
is_dir($p) | It is a folder |
is_readable($p) | PHP may read it |
is_writable($p) | PHP may write to it |
<?php
mkdir("folder");
file_put_contents("data.txt", "x");
var_dump(is_file("data.txt"));
var_dump(is_file("folder"));
var_dump(is_dir("folder"));
var_dump(is_readable("data.txt"));
bool(true)
bool(false)
bool(true)
bool(true)
Delete a file: unlink()
<?php
file_put_contents("temp.txt", "x");
if (is_file("temp.txt")) {
unlink("temp.txt");
}
var_dump(file_exists("temp.txt"));
bool(false)
Rename or move: rename()
<?php
file_put_contents("old-name.txt", "x");
rename("old-name.txt", "new-name.txt");
var_dump(file_exists("old-name.txt"), file_exists("new-name.txt"));
bool(false)
bool(true)
rename() also moves a file to another folder.
Copy: copy()
<?php
file_put_contents("original.txt", "content");
copy("original.txt", "backup.txt");
echo file_get_contents("backup.txt");
content
Race conditions
Checking first and acting later has a small gap. Another process could delete the file in between.
<?php
if (file_exists($file)) { // check
$data = file_get_contents($file); // use: the file might be gone now
}
For important code, just try the action and handle failure:
<?php
$data = @file_get_contents("maybe-missing.txt");
if ($data === false) {
echo "File not available";
}
File not available
Temporary files
<?php
$temp = tempnam(sys_get_temp_dir(), "demo_");
file_put_contents($temp, "short-lived");
echo file_get_contents($temp) . "\n";
unlink($temp);
var_dump(file_exists($temp));
short-lived
bool(false)
tempnam() creates a unique file in a folder you choose, which is safe from name clashes.
Deleting with user input
unlink($_GET["file"]) lets a visitor delete any file PHP may touch. Never build a path from input. Use IDs mapped to files you stored yourself.