What are some common pitfalls when trying to display images in emails using PHP?

Common pitfalls when trying to display images in emails using PHP include not properly setting the Content-Type header to indicate that the email contains HTML content, not using absolute URLs for image sources, and not properly encoding the image data if it is included inline. To solve these issues, make sure to set the Content-Type header to "text/html" when sending HTML emails, use absolute URLs for image sources, and properly encode the image data using base64 encoding if including images inline.

// Set the Content-Type header to indicate HTML content
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Use absolute URLs for image sources
$imageUrl = "https://example.com/image.jpg";

// Encode the image data using base64 encoding if including images inline
$imageData = file_get_contents($imageUrl);
$base64Image = base64_encode($imageData);

// Include the image in the email HTML content
$htmlContent = '<img src="data:image/jpeg;base64,' . $base64Image . '" />';

// Send the email with the proper headers and HTML content
mail($to, $subject, $htmlContent, $headers);