What potential issues can arise when using $_FILES[] in PHP for file uploads?

One potential issue when using $_FILES[] in PHP for file uploads is the lack of proper validation and sanitization of the uploaded file. This can lead to security vulnerabilities such as allowing malicious files to be uploaded and executed on the server. To solve this issue, it is important to validate the file type, size, and content before moving the file to its final destination on the server.

// Example of validating and sanitizing file upload using $_FILES[] in PHP

if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Validate file type
    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
    $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
    if(!in_array($fileExtension, $allowedExtensions)) {
        die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
    }

    // Validate file size
    $maxFileSize = 2 * 1024 * 1024; // 2MB
    if($file['size'] > $maxFileSize) {
        die('File size exceeds the limit of 2MB.');
    }

    // Move the file to its final destination
    $uploadPath = 'uploads/' . $file['name'];
    if(move_uploaded_file($file['tmp_name'], $uploadPath)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
}