What best practices should be followed when creating an image upload script that displays HTML code?

When creating an image upload script that displays HTML code, it is important to sanitize user input to prevent cross-site scripting (XSS) attacks. This can be done by using functions like htmlspecialchars() to escape special characters in the HTML code. Additionally, it is recommended to validate the file type and size before uploading it to the server to ensure security and prevent malicious uploads.

// Sanitize user input to prevent XSS attacks
$html_code = htmlspecialchars($_POST['html_code']);

// Validate file type and size before uploading
if ($_FILES['image']['type'] == 'image/jpeg' || $_FILES['image']['type'] == 'image/png' && $_FILES['image']['size'] < 5000000) {
    // Upload image to server
    move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $_FILES['image']['name']);
    
    // Display HTML code with uploaded image
    echo $html_code;
    echo '<img src="uploads/' . $_FILES['image']['name'] . '" alt="Uploaded Image">';
} else {
    echo 'Invalid file type or size. Please upload a JPEG or PNG image under 5MB.';
}