Upload default photo if no photo is registered

Asked

Viewed 77 times

-3

Hello, how do I upload a default photo for viewing if I haven’t registered a customer photo?

I bring the image to the viewing like this:

<img src="fotos/<?php echo $dados["foto"]; ?>" width='120' />
So if I don’t register a photo for the client, it will upload a default photo.

  • You can use: if..else, ternary or null coalesces Operator

  • Yes, but how? I tried some things and could not, so I asked here for some example in what I put

4 answers

3

If you are using PHP 7, you can use null coalescence operator to check if there is any value in your variable and, if not, display a default value.

<img src="fotos/<?= $dados["foto"] ?? "default.png" ?>" width='120' />

I also used to replace the structure <?php echo for <?=, which are equivalent.

See more in Difference between php <?php tags and <?=

Note: The image will be displayed default.png only if $dados["foto"] is null or not defined. Values such as "", false, etc would be considered valid. You can use the operator ?: or make all necessary conditions manually.

0

Make a IF...Else checking whether the value passed $dados["foto"] is null, you assign to the $dados["foto"] a standard image:

$dados["foto"] = "caminhodasuaimagem.extensão"

0


Hello, as mentioned in the comments, you can do this easily using if and else, follows an example:

<?php 

if (!empty($dados['foto'])) { 
    echo "<img src='".$dados['foto']."'/>";
}

else {
    echo "<img src='linkdaimagempadrao.png'/>";
}

?>

If there is data in the widget foto, will be displayed, if not, the image of the else. Remembering that I would need to be inside a while and passing the correct parameters.

Always put in the full code, to facilitate the people who will help you, and help yourself to review your code.

-1

Samuel solved yes, yesterday I had found a solution, and it works here in php 7.3, but I found its code cleaner. What I had put down was this.

<?php if($foto){ ?>

<img src="fotos/<?php echo $dados["foto"]; ?>" width='120' />

  <?php }else{ ?>
  
<img src="fotos/sem_foto.jpg" width='120'>

<?php } ?>

Today I took yours and adapted.

<?php 

if (!empty($dados['foto'])) { 
    echo "<img src='fotos/".$dados['foto']."' width='120'/>";
}

else{
    echo "<img src='fotos/sem_foto.jpg' width='120'/>";
}

?>

I don’t know if the two are okay, they work, but I don’t know which is the best, although I find your cleaner

Browser other questions tagged

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