What best practices should be followed when handling file uploads and deletions in PHP to ensure data security and integrity?

When handling file uploads and deletions in PHP, it is important to follow best practices to ensure data security and integrity. This includes validating file types, sanitizing file names, storing files outside of the web root directory, using unique file names to prevent overwriting, and implementing proper permissions for file access.

// File Upload
$uploadDir = 'uploads/';
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];

if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    
    $fileName = basename($file['name']);
    $fileType = pathinfo($fileName, PATHINFO_EXTENSION);
    
    if(in_array($fileType, $allowedTypes)) {
        $uploadPath = $uploadDir . uniqid() . '.' . $fileType;
        
        if(move_uploaded_file($file['tmp_name'], $uploadPath)) {
            echo 'File uploaded successfully.';
        } else {
            echo 'Error uploading file.';
        }
    } else {
        echo 'Invalid file type.';
    }
}

// File Deletion
$fileToDelete = 'uploads/file.jpg';

if(file_exists($fileToDelete)) {
    if(unlink($fileToDelete)) {
        echo 'File deleted successfully.';
    } else {
        echo 'Error deleting file.';
    }
} else {
    echo 'File does not exist.';
}