Skip to content

PHP Tutorial File Handling

Checking and Managing Files

Lesson 169 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Before you read or change a file, check that it is there and that you may use it.

Does it exist?

index.php
PHP
<?php
file_put_contents("data.txt", "x");

var_dump(file_exists("data.txt"));
var_dump(file_exists("nothing.txt"));
Output
OUTPUT
bool(true)
bool(false)

file_exists() is true for files and folders. To be precise, use these:

FunctionTrue 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
index.php
PHP
<?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"));
Output
OUTPUT
bool(true)
bool(false)
bool(true)
bool(true)
index.php
PHP
<?php
file_put_contents("temp.txt", "x");

if (is_file("temp.txt")) {
    unlink("temp.txt");
}

var_dump(file_exists("temp.txt"));
Output
OUTPUT
bool(false)

Rename or move: rename()

index.php
PHP
<?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"));
Output
OUTPUT
bool(false)
bool(true)

rename() also moves a file to another folder.

Copy: copy()

index.php
PHP
<?php
file_put_contents("original.txt", "content");

copy("original.txt", "backup.txt");

echo file_get_contents("backup.txt");
Output
OUTPUT
content

Race conditions

Checking first and acting later has a small gap. Another process could delete the file in between.

index.php
PHP
<?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:

index.php
PHP
<?php
$data = @file_get_contents("maybe-missing.txt");

if ($data === false) {
    echo "File not available";
}
Output
OUTPUT
File not available

Temporary files

index.php
PHP
<?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));
Output
OUTPUT
short-lived
bool(false)

tempnam() creates a unique file in a folder you choose, which is safe from name clashes.

dangerous
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.