How to delete a file via PHP?

How to delete a file via PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The Unlink Trap: Why Your Relative Paths Fail in PHP

Attempting to delete a file from a different directory using unlink() is a common scenario, yet it frequently results in the dreaded "file does not exist" error. In your specific case, where you are trying to remove public_files/22.pdf from within projects/backend/removeProjectData.php, the culprit is almost certainly how you are constructing the path string.

The line of code unlink('../../public_files/' . $fileName); relies on relative paths that are interpreted by the PHP process, not necessarily the browser request. The critical distinction lies between the script's execution location and its current working directory (CWD). When a user requests a file via HTTP, the CWD is typically set to the document root of your web server, not the directory where removeProjectData.php resides.

If your web server's document root is /var/www/html, accessing projects/backend/removeProjectData.php sets the CWD to /var/www/html. Consequently, when PHP evaluates the relative path string '../../public_files/', it traverses up two levels from the document root and then looks for a folder named public_files. Unless your directory structure specifically mirrors that exact traversal from the web root, the resulting resolved path will point to a non-existent location on the disk.

The most robust solution is to use absolute paths derived directly from the script's execution context. By utilizing PHP's built-in constants and functions, you ensure the path resolution happens within the context of the script itself, regardless of how the web server configured the CWD.

You can construct the absolute path using __DIR__ (or dirname(__FILE__) in older versions) combined with realpath(). This two-step process resolves any symbolic links and ensures you are pointing to the canonical location on the filesystem. Here is the corrected approach:

<?php
// Define the directory relative to the script itself
$relativePath = '../public_files/'; 

// Resolve the absolute path based on where this script is running
$absolutePath = realpath(__DIR__ . $relativePath) . '/' . $fileName;

// Attempt deletion only if the file actually exists at that absolute location
if (file_exists($absolutePath)) {
    unlink($absolutePath);
    
    // Log or handle success
    echo "File deleted successfully.";
} else {
    // Log error or handle missing file gracefully
    error_log("Cannot delete file: $absolutePath");
}
?>

This method eliminates the ambiguity of relative navigation. __DIR__ provides the directory containing the current file, and appending the relative segment constructs the correct sub-path. Wrapping the operation in an existence check is crucial; attempting to unlink a non-existent file generates a warning that can clutter your error logs or expose sensitive file paths if not handled carefully.

There are also permission considerations to keep in mind. Even with the correct path, unlink() will fail silently (or throw a warning depending on your error reporting settings) if the operating system user running the web server lacks write permissions for the parent directory. Ensure that the directory containing the file is writable by the web server process (e.g., www-data or apache).

If you are working within the Laravel ecosystem, the standard practice differs slightly. Instead of manually handling file paths and deletion logic in a controller or script, you should leverage the filesystem facade provided by the framework. This abstracts away the underlying path resolution and handles permission checks more gracefully:

use Illuminate\Support\Facades\File;

// Recommended approach in Laravel
File::delete(public_path('22.pdf')); 

Using the public_path() helper guarantees that you are referencing a location relative to the application root, which is distinct from the document root. This separation of concerns ensures that your deployment structure doesn't break your file management logic.

Ultimately, relying on absolute paths constructed via __DIR__ or framework helpers prevents the "file not found" errors caused by mismatched working directories. Always validate the existence of the target before attempting deletion to maintain application stability and security.

Our network