Reserve image - SRC

Asked

Viewed 76 times

2

I’m wondering if it’s possible to create a secondary image if the main image doesn’t exist

In case, if someone registers and does not put photo, he set a default img.

<img src="assets/images/<?= $username ?>.png" alt="" class="user-avatar-md rounded-circle">

has any possibility that I can do 2 SRC ? and when the name.png file is not found it overwrite by

<img src="assets/images/avatar-1.jpg" alt="" class="user-avatar-md rounded-circle">

2 answers

3


You can check in PHP itself if the image file exists:

<img src="assets/images/<?=file_exists("$username.png") ? "$username.png" : "avatar-1.jpg" ?>" alt="" class="user-avatar-md rounded-circle">

The file_exists("$username.png") will fetch the PNG image with the name in the variable $username, if not, it will show the image avatar-1.jpg. But it will only work if the option allow_url_fopen is on in php.ini.

-1

Simple, make a if by checking whether the variable $username has some value, which in the case is the name of the image, if there is no content in the variable add the link to the default image.

<?php
 if(!isset($username)){
 $username = "link/para/imagem/padrão";
 } 
?>
  • all variable "$username" has value, but in the files of the site, the image may not exist, so it will return the value, example: test.png, but on the site there is no test.png, so it would be without image

  • Wow, why did your Edit copy the solution of my answer? And even put a capenga solution.

  • kkkkk, I didn’t notice. More respect for my answer. I will "desedite"

  • But you can see who answered first? I hadn’t even noticed your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.