What are potential security risks associated with file uploads in PHP and how can they be mitigated?

One potential security risk associated with file uploads in PHP is the possibility of allowing malicious files to be uploaded to the server, which can then be executed or used to compromise the system. To mitigate this risk, it is important to validate file types, limit file sizes, and store uploaded files outside of the web root directory.

// Validate file type and limit file size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 1048576; // 1MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
    // Store uploaded file outside of web root directory
    move_uploaded_file($_FILES['file']['tmp_name'], '/path/to/uploaded/files/' . $_FILES['file']['name']);
    echo 'File uploaded successfully.';
} else {
    echo 'Invalid file type or file size too large.';
}