Are there any best practices for handling file management in PHP applications to ensure efficiency and security?

To ensure efficiency and security in file management in PHP applications, it is important to sanitize user input, validate file types, set proper file permissions, and use secure file paths. Additionally, it is recommended to store sensitive files outside of the web root directory to prevent direct access.

// Example of sanitizing user input and validating file type
$allowed_extensions = array('jpg', 'jpeg', 'png');
$uploaded_file = $_FILES['file']['name'];
$extension = pathinfo($uploaded_file, PATHINFO_EXTENSION);

if (!in_array($extension, $allowed_extensions)) {
    die('Invalid file type. Please upload a JPG, JPEG, or PNG file.');
}

// Example of setting proper file permissions
$filename = 'example.txt';
if (file_exists($filename)) {
    chmod($filename, 0644);
}

// Example of using secure file paths
$upload_dir = '/var/www/uploads/';
$target_file = $upload_dir . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}