What security measures should be taken when using PHP to handle user input for file uploads?

When handling user input for file uploads in PHP, it is important to implement security measures to prevent malicious code execution or unauthorized access to the server. One common security measure is to validate the file type and size before allowing the upload. Additionally, it is recommended to store the uploaded files outside of the web root directory to prevent direct access.

// Check if the file type is allowed
$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.');
}

// Check if the file size is within limits
$maxFileSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size exceeds limit. Maximum file size is 5MB.');
}

// Move the uploaded file to a secure directory
$uploadDir = '/path/to/secure/directory/';
$uploadedFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFile)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Failed to upload file.';
}