What are the potential security risks associated with uploading files to a server using PHP?

One potential security risk associated with uploading files to a server using PHP is the possibility of allowing malicious files to be uploaded and executed on the server, leading to security vulnerabilities such as code injection or remote code execution. To mitigate this risk, it is important to validate the file type and size before allowing the upload to proceed.

// Validate file type and size before uploading
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'gif'];
$maxFileSize = 5 * 1024 * 1024; // 5MB

if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedFileTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    // Upload file to server
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    echo 'File uploaded successfully.';
} else {
    echo 'Invalid file type or size.';
}