ZoRky
ZoRky

Reputation: 28

check if img loaded successfully or not using php

How to check if the image loaded or not using php.

i'm using this

<img onload="myFunction1()" onerror="myFunction2()" src="https://www.google.com/img.png">

but Need it pure php not html tags

Upvotes: 0

Views: 1770

Answers (1)

Martin
Martin

Reputation: 22760

How to check if the image loaded or not using php.
i'm using this
<img onload="myFunction1()" onerror="myFunction2()" src="https://www.google.com/img.png">

but Need it pure php not html tags

Some points:

1) It looks like you're trying to check the image is loaded in the browser, this can not be done with PHP because PHP is server-side and only the output of PHP code is sent to the browser.

2) Why are you trying to use PHP when javascript should do?

3) If you have some obscure technical requirement for the test to be PHP then you could do it using some AJAX requests but it would be horrifically inefficient compared to simply having some browser-run javascript without needing to converse with the server, again.

  • It is worth noting even if you did construct a PHP + Javscript based ajax test for if an image was loaded by a browser; the result would be useless because the result could not be actioned by PHP as previously stated, PHP works on the page before the page reaches the client browser.
    It's like drinking a whole cup of coffee and only then telling the Barista that it was too hot.

4) Use Javascript.

You can do this check before the page is sent to the browser:

If you simply want to check that https://www.google.com/img.png exists and is accessible you can do this in PHP; with some caveats. You can use cURL (read the top three answers they're all useful) Or you can use PHP getimagesize or get_headers as outlined in this answer to a similar question.

Once you have established if the image specified is valid and reachable you can then use PHP to choose an outcome and change the contents of the page sent to the browser, before the page is sent, typically with an if statement to display different images depending on their validity.

Upvotes: 2

Related Questions