Delete a File
Deletes one existing file only after realpath() confirms it is a file under an approved base directory.
Purpose
Deletes one existing file only after realpath() confirms it is a file under an approved base directory.
Snippet details
ContextFile SystemLevelPracticalCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Delete a File.
*
* Purpose:
* Deletes one approved local file.
*
* @param string $file_path Candidate file path.
* @param string $base_dir Approved base directory.
* @return array Delete result.
*/
function ogSnippetDeleteAFile(string $file_path, string $base_dir): array {
$result = array(
'ok' => false,
'message' => 'File was not deleted.'
);
$resolved_base = realpath($base_dir);
$resolved_file = realpath($file_path);
if ($resolved_base === false || $resolved_file === false) {
$result['message'] = 'File path could not be resolved.';
return $result;
}
if (strpos($resolved_file, $resolved_base) !== 0) {
$result['message'] = 'File is outside the approved directory.';
return $result;
}
if (is_file($resolved_file) === false) {
$result['message'] = 'Target is not a file.';
return $result;
}
if (is_writable($resolved_file) === false) {
$result['message'] = 'File is not writable.';
return $result;
}
if (unlink($resolved_file) === true) {
$result['ok'] = true;
$result['message'] = 'File was deleted.';
}
return $result;
}
$delete_report = ogSnippetDeleteAFile(__DIR__.'/old_serenity_manifest.tmp', __DIR__);
echo 'Delete status: '.$delete_report['message'];