Deleting a File using php/codeigniter

Deleting a File using php/codeigniter

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

Stefan Bogdanescu

Founder & Senior Architect

Deleting Files in CodeIgniter: Handling unlink() Safely

When working with file system operations in a web application, deleting a file is often more dangerous than creating one. A simple oversight can lead to data loss or, worse, security vulnerabilities if the wrong path is constructed. In your specific case, you have identified localhost/project/folder/file_to_delete as the target and are considering PHP's native unlink() function. While unlink() is indeed the correct low-level tool for removing files, integrating it directly into a CodeIgniter application requires careful attention to how paths are resolved and how user input is sanitized.

The core concept behind unlink() is straightforward: it removes a file from the filesystem based on an absolute or relative path string. However, the function does not inherently know about your web root or your project structure unless you tell it where to look. If you pass a raw string like "file_to_delete" without context, PHP will attempt to delete a file in the current execution directory (often htdocs), which is almost certainly not what you want.

In CodeIgniter, the most robust approach is to leverage the framework's built-in path helper functions rather than constructing paths manually with string concatenation. Manual concatenation is prone to errors regarding trailing slashes and different operating systems' path separators. Instead, use PATH_INFO (deprecated in newer PHP versions) or, more reliably, FOLDER_PATH() combined with base paths.

However, the most critical step before calling any filesystem function is determining the absolute path to the file relative to your document root. You can achieve this by utilizing the base_path() helper provided by CodeIgniter. This helper returns the full path to the directory where your application resides. From there, you can append your specific folder and filename to create a secure, absolute path.

Here is a practical pattern for implementing deletion within a Controller:

use CodeIgniter\Controller;

class Files extends Controller
{
    public function delete()
    {
        // Ensure the file parameter exists
        if (!$this->request->hasPost('file')) {
            return response()->view('error', ['message' => 'No file specified']);
        }

        $filename = $this->request->getPost('file');

        // Define the folder relative to your project root
        // Adjust 'folder' to match your actual directory structure
        $relativePath = 'project/folder/' . $filename;

        // Get the absolute path using CodeIgniter's base_path helper
        $absolutePath = rtrim(base_path(), DIRECTORY_SEPARATOR) . '/' . ltrim($relativePath, '/');

        // Verify the file exists before attempting deletion to prevent errors
        if (!file_exists($absolutePath)) {
            return response()->view('error', ['message' => 'File not found']);
        }

        // Attempt to delete the file
        if (unlink($absolutePath)) {
            return response()->json(['success' => true, 'message' => 'File deleted successfully']);
        } else {
            return response()->view('error', ['message' => 'Failed to delete file. Check permissions.']);
        }
    }
}

This implementation prioritizes safety by first verifying the file's existence. Calling unlink() on a non-existent file triggers a warning in PHP, which can clutter your error logs and potentially expose sensitive system information to clients if not handled via an error page or debug flag configuration. Additionally, checking permissions is implicitly handled here; if the web server user lacks write/delete access to that directory, unlink() will return false, allowing your application to gracefully report the failure rather than crashing.

One significant trade-off to consider involves file permissions. Even on a localhost environment, the operating system enforces strict rules about who can delete files. The PHP process usually runs as a specific user (like www-data or _httpd). If the folder containing your file is owned by root with restricted permissions, the script will fail regardless of the logic in your code. Always ensure the directory has appropriate execute and write permissions for the web server user.

Security-wise, relying on the raw filename passed from the user input without validation is a risk. While this example assumes $filename comes from a controlled source or is validated elsewhere, always consider sanitizing inputs to prevent directory traversal attacks (e.g., someone passing ../../../etc/passwd). Using a whitelist of allowed extensions or validating against a specific path structure mitigates these risks effectively.

For more complex scenarios involving multiple files or recursive deletion of directories within CodeIgniter, you might look into the Filesystem helper class or third-party libraries. However, for single file deletion, sticking to the native unlink() function with proper path resolution via base_path() remains the most efficient and standard practice.

Our network