[…]" /> PHP: Handle broken image links on a page - Webner Blog

PHP: Handle broken image links on a page

Author - Webner
14.02.2020
|
0 Comments
||

Broken image link issue

While creating a website or any project, we usually need to add some images to it. Suppose we have a Laravel project where we are showing some images from s3 or somewhere else.

We may include the image in HTML tag like this below code:

@if(isset($data['picture']) )
    	<img src="{{ $data['picture'] }}"/>
@endif	

This works fine to show an image. But if the image does not exist then it will show a broken image link.
php broken image 1
To avoid this situation, we can add the alt attribute of image tag like this:

<img src="{{ $data['picture'] }}" alt=”Data Picture” />

In this case, the text written in the alt attribute will display along with the broken link which will describe the image that is not found.
php broken image 2

But the broken link will still appear on our screen along with the alt attribute text.

How to solve this?

One way to solve this broken image link issue is to use a default image in its place whenever the image does not exist. We will have to check whether the link has an image or not.
One possible solution is that we can simply check for the URL if it is valid or not. But sometimes a situation arises when the URL is valid but still does not contain an image.

Therefore, we can use a function file_get_contents to check whenever the image link is valid but the image does not exist there.

For this purpose, we will need to check for the contents of the image before showing it. If the image content is available on the URL then it will show the image otherwise will show a default image.

For example:

@if(isset($data['picture']) && (@file_get_contents($data['picture'])))
    	<img src="{{ $data['picture'] }}" class="card-img-top" />
@else
    	<img src="{{ asset('placeholder.jpg') }}" class="card-img-top" />	
@endif	

Here, in the above code, we have used a function file_get_contents which will check for the contents of the image on the given URL. It will return false if the image does not exist there.
In that case, we have set a default image.
php broken image 3

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *