What are the best practices for handling file uploads in PHP to ensure proper permissions and security?

When handling file uploads in PHP, it is important to ensure proper permissions and security to prevent unauthorized access or execution of malicious files. One way to do this is by setting appropriate file permissions on the server to restrict access to uploaded files. Additionally, validating file types and using functions like move_uploaded_file() to store uploads in a secure directory can help mitigate security risks.

// Example code snippet for handling file uploads in PHP with proper permissions and security

// Set the upload directory
$uploadDir = 'uploads/';

// Validate file type
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (!in_array($uploadedFileType, $allowedTypes)) {
    die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}

// Move uploaded file to secure directory
$uploadFilePath = $uploadDir . basename($_FILES['file']['name']);

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