What best practice should be followed when deleting files from a server after deleting content from a database in PHP?
When deleting content from a database in PHP, it is important to also delete any associated files from the server to prevent orphaned files. To ensure this is done properly, you should first query the database to get the file paths of the files to be deleted, then unlink those files from the server using the unlink() function in PHP.
// Get file paths from database
$query = "SELECT file_path FROM files WHERE content_id = :content_id";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':content_id', $content_id);
$stmt->execute();
$files = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Delete files from server
foreach($files as $file) {
if(file_exists($file['file_path'])) {
unlink($file['file_path']);
}
}