What potential security risks are involved in allowing users to upload files via PHP?

Allowing users to upload files via PHP can pose security risks such as malicious file uploads, potential server vulnerabilities, and the execution of harmful scripts. To mitigate these risks, it is essential to validate file types, limit file sizes, and store uploaded files in a secure directory outside of the web root.

<?php
$uploadDir = 'uploads/';
$allowedTypes = ['jpg', 'jpeg', 'png'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileName = $_FILES['file']['name'];
    $fileSize = $_FILES['file']['size'];
    $fileType = pathinfo($fileName, PATHINFO_EXTENSION);

    if ($fileSize <= $maxFileSize && in_array($fileType, $allowedTypes)) {
        $uploadPath = $uploadDir . basename($fileName);
        move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);
        echo 'File uploaded successfully.';
    } else {
        echo 'Invalid file type or size.';
    }
} else {
    echo 'Error uploading file.';
}
?>