How can fopen and unlink functions be effectively utilized in PHP to handle file creation and deletion processes securely?
When using fopen and unlink functions in PHP to handle file creation and deletion processes securely, it is important to validate user input and sanitize file names to prevent directory traversal attacks. Additionally, setting proper file permissions and using absolute file paths can help enhance security.
// Example of securely creating a file using fopen
$filename = 'example.txt';
$filepath = '/path/to/directory/' . $filename;
if (strpos($filename, '/') !== false) {
die("Invalid file name");
}
$handle = fopen($filepath, 'w');
fclose($handle);
// Example of securely deleting a file using unlink
$filename = 'example.txt';
$filepath = '/path/to/directory/' . $filename;
if (strpos($filename, '/') !== false) {
die("Invalid file name");
}
if (file_exists($filepath)) {
unlink($filepath);
} else {
die("File does not exist");
}