Skip to content
PHP Logo

How can PHP developers ensure that image URLs are properly formatted for display on a website?

When displaying images on a website, PHP developers should ensure that the image URLs are properly formatted to avoid broken images. One way to achieve this is by using the PHP function `filter_var()` with the `FILTER_VALIDATE_URL` filter to validate the image URL. Additionally, developers can use the `htmlspecialchars()` function to sanitize the URL and prevent any potential XSS attacks.

php
$image_url = "https://example.com/image.jpg";

if (filter_var($image_url, FILTER_VALIDATE_URL)) {
    echo '<img src="' . htmlspecialchars($image_url) . '" alt="Image">';
} else {
    echo 'Invalid image URL';
}