What potential pitfalls should be considered when setting the path for file uploads in PHP?

When setting the path for file uploads in PHP, it is important to consider potential security risks such as allowing users to upload files to sensitive directories or executing malicious code. To mitigate these risks, it is recommended to set a specific upload directory outside of the web root, validate file types and sizes, and sanitize file names.

// Set the upload directory outside of the web root
$uploadDirectory = '/var/www/uploads/';

// Validate file type and size
$allowedTypes = ['jpg', 'jpeg', 'png'];
$maxFileSize = 1048576; // 1MB

if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    // Sanitize file name
    $fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadDirectory . $fileName);
} else {
    echo 'Invalid file type or size.';
}