What are best practices for storing uploaded images securely in PHP?

When storing uploaded images securely in PHP, it is important to validate the file type, restrict file permissions, and store the files outside of the web root directory to prevent direct access. Additionally, generating unique file names and using a secure file upload library can help mitigate security risks.

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}

// Move uploaded file to secure directory
$uploadDir = '/path/to/uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);

// Set secure file permissions
chmod($uploadFile, 0644);