What are some common pitfalls or mistakes to avoid when implementing a file upload feature with preview functionality in PHP?

One common pitfall to avoid when implementing a file upload feature with preview functionality in PHP is not properly validating the uploaded file before displaying it. This can lead to security vulnerabilities such as allowing malicious files to be uploaded and executed on the server. To prevent this, always validate the file type and size before processing or displaying it.

// Validate the uploaded file before displaying it
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // Check file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if(!in_array($file['type'], $allowedTypes)) {
        echo 'Invalid file type. Please upload a JPEG, PNG, or GIF file.';
        exit;
    }

    // Check file size
    if($file['size'] > 5242880) { // 5MB
        echo 'File is too large. Please upload a file smaller than 5MB.';
        exit;
    }

    // Display the uploaded file
    echo '<img src="' . $file['tmp_name'] . '" alt="Uploaded Image">';
}