-1

Im trying to use a fallback image with javascript inside a php echo, but Im confused with the quotes, what´s the proper way to write this syntax to make it work?

echo '<img class="rounded img-fluid" src="'.$user_image_src.'" alt="User Image" onerror="this.onerror=null; this.src='Fallback.jpg'">';
SilverSurfer
  • 4,281
  • 6
  • 24
  • 50

4 Answers4

4

Use symbol escaping (\'):

echo '<img class="rounded img-fluid" src="'.$user_image_src.'" alt="User Image" onerror="this.onerror=null; this.src=\'Fallback.jpg\'">';
2

Dealing with nested quotes is a pain. Dealing with multiple layers of nested quotes is a nightmare. Try to avoid it whenever possible.

  1. Don't use echo when you can drop out of PHP mode
  2. Escape data when passing it into HTML

So:

<img 
    class="rounded img-fluid" 
    src="<?php echo htmlspecialchars($user_image_src); ?>"
    alt="User Image"
    data-fallback="Fallback.jpg"
    onerror="this.onerror=null; this.src=this.dataset.fallback;">
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

To Avoid the confusion with quotes, try something like this:

 <img src="<?php echo $user_image_src; ?>" alt="Image not found" 
 onerror="this.onerror=null;this.src='Fallback.jpg';" />
Manas
  • 3,060
  • 4
  • 27
  • 55
0

Just change this part, this.src='Fallback.jpg;' to this.src="Fallback.jpg". Use single quotes for most of the time in php. When it's mysql query, use double quotes instead. For echo-ing out the html, just use single quote to enclose the string and for html attributes uses double quote to avoid your confusion.

However, if possible, try to avoid echo out html elements using php.

druyal96
  • 1
  • 3