How to not show img element where src is equal to null

Asked

Viewed 1,481 times

3

I’m making a system where the user can post images, texts, etc...but in the system every image posted should be uploaded to the server and the user can delete them.

With the exclusion of the server image then the posts containing such an image present error 404.

I know it is possible to display a standard image for images not found via .htaccess but what I want is to show neither error nor standard image, simply not show the img.

The system is thus structured:

Page home.php

<?php
ob_start('ob_gzhandler');
session_start();
header ('Content-type: text/html; charset=UTF-8');

if(isset($_GET['last_msg_id'])){
   $last_msg_id = $_GET['last_msg_id'];
}
if(isset($_GET['action'])){
   $action=$_GET['action'];
}else{ 
   $action = ''; 
}

if($action != "get"){
?>
   <div id="coisaEstranha" style="margin-top:2%;">
                 <?php include('load_first.php'); ?>
                 <div id="last_msg_loader"></div>
            <?php }else{ include('load_second.php');exit();}?>
   </div>

<script type="text/javascript">
$(function(){   
    function last_msg_funtion(){
      if($('#last_msg_loader img').length){
         return;
      }
      var ID = $(".message_box:last").attr("id");

      $.post("home.php?action=get&last_msg_id="+ID, function(data){
          if (data != "") {
             $(".message_box:last").after(data);     
          }
          $('#last_msg_loader').empty();
      });
    };

    $(window).scroll(function(){
        if  ($(window).scrollTop() == $(document).height() - $(window).height()){
           last_msg_funtion();
        }
    });     

    var refreshId = setInterval(function() {
     // Caso scroll seja maior que 150 pixels
     if($(window).scrollTop() < 150){
         $("#coisaEstranha").load('load_first.php');
     }
   }, 60000);

}); 
</script>

Page load_first.php

<?php
header ('Content-type: text/html; charset=UTF-8');
$Busca = $pdo->query("SELECT * FROM posts ORDER By id DESC LIMIT 15");
$Busca->execute();

while($fetch = $Busca->fetch(PDO::FETCH_ASSOC)){    
     $msgID= $fetch['id'];
     $msg= $fetch['content'];
    ?>
    <div id="<?php echo $msgID; ?>" class="message_box" >
   <div>
         <div id="xiao"><?php echo $msg; ?></div><!-- ESTA STRING TRÁS A POSTAGEM! -->   
         <input id="id_post" type="hidden" value="<?php echo $id_post;?>">
       </div> 
    </div>    
    <?php
}
?>

Page load_second.php

<?php
header ('Content-type: text/html; charset=UTF-8');
$last_msg_id=$_GET['last_msg_id'];

$Busca = $pdo->query("SELECT * FROM posts WHERE id < '$last_msg_id' ORDER By id DESC LIMIT 15");
$Busca->execute();

while($fetch = $Busca->fetch(PDO::FETCH_ASSOC)){
    $msgID= $fetch['id'];
    $msg= $fetch['content'];
    ?>
    <div id="<?php echo $msgID; ?>" class="message_box" >
       <div>        
         <div id="xiao"><?php echo $msg; ?></div><!-- ESTA STRING TRÁS A POSTAGEM! -->    
         <input id="id_post" type="hidden" value="<?php echo $id_post;?>">
       </div> 
    </div>
    <?php
}
?>
  • 1

    The correct would be to test via PHP if the image exists, for example by testing with file_exists, depends on how your structure looks, more if you do it in your CSS img[src=""]{display:none;}, images with attributes src voids will not be displayed, see http://jsfiddle.net/9vm8761c/

  • The images come from DB because they are saved with the img tag and its respective src...I tried to use your example of Jsfiddle but it did not work in a global way nor attributing exclusively to the ID of the div that displays the posts :(

  • 1

    Show an output of your code as the tag img.

  • The rendered image is simple I make no changes if I do not limit the width to use the maximum available inside the parent div which is limited in pixels...ex: 420px. <img src="path/image.png" width="100%">

  • Just a touch, Lauro, your question has code too not related to the problem. Gives a check on how to do Minimum, Complete and Verifiable Example.

  • Thanks for the "touch', initially I put no bad code I think the staff did not understand how to return and structure my code...when I get to the PC again I will try to clean the classes in Divs to get more "lean".

  • It would not only be making a conditional checking the existence of the image before the (echo $img) <- example ?

  • Unfortunately not @Zebradomal ...the "$" string that brings the content of the post brings numerous elements and there may be several images not only one.

  • Please indent and clear your code at all times. It’s better for you to understand and fix the code, and help those who want to help you, because you don’t need to decipher the logic of the program.

Show 4 more comments

3 answers

5


The correct, I believe would be to test via PHP if the image exists, testing for example with file_exists, depends on how your structure is.

You can even put in your CSS so that images with the attribute src voids are not displayed, example:

img[src=""]{display:none;}

Jsfiddle

If in your database is saved the image including the tag img, a solution would be to parse HTML with PHP and get the src, then test if the image exists, example:

$img = '<img src="caminho/imagem.png" />';
$dom = new DOMDocument();
$dom->loadHTML($img);
$imagem = $dom->getElementsByTagName('img')->item(0)->getAttribute('src');

if(file_exists($imagem)){
    //exibe a imagem
}

EDIT

Another option would be to rewrite the image with htaccess to a 1x1 transparent pixel png image, example:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule \.(gif|jpe?g|png|bmp) ../img/invisivel.png [NC,L]
  • Your example is functional with static html but with img tag coming from DB and displayed by "print_" or "echo" not.

  • @Lauromoraes I edited the answer, check if this solves the problem.

  • In his new example it would serve if it were the case of a cover image that returns in a single string after a query, but my case is an html element within a string along with several others (other images, texts, video iframes, etc...). The social feed style posting template.

  • I posted in Pastebin if you have time to take a look at the string "$content" Pastebin

  • @Lauromoraes, I’m on mobile now I can not test, but you said q can change the image to a pattern with htaccess, q vc could do is hide the default image with CSS, img[src="padrao.png"]{display:none}

  • I was tempted to test this bad tip the . htaccess leads to the link that in the case no longer exists displaying the default image set on it in place of what would be the original image. O . htaccess does not link the default image set on it in the src of the images that are deleted from the disk...but thanks for the help, for now I am trying to resort to DOM with js...if give I return solution.

  • @Lauromoraes another option would be to rewrite the image with htaccess to a 1x1 transparent pixel png image, it seems to work :P

  • Sorry for the delay in replying to your submitted solution. A transparent png of 1x1 no . htaccess solved the problem o/ ! You could attach this answer in your "reply" so I can mark as accepted. Thank you :)

  • @Lauromoraes, how good that it worked, I edited the answer.

Show 4 more comments

0

Create a blank default image and check to see if the src image has something, if not, put the image blank.

<?php

$imagem = $variavel['imagem_do_banco'];

if($imagem == '' or empty($imagem)){
echo '<img src="imagem_padrao.jpg">';
}else{
echo '<img src="'.$imagem.'">';
}
?>

Or try putting a Hidden in the style tag <img>

<?php

$style = ($variavel['imagem_banco'] == '') ? 'display:none;' : 'display:block';
$image = $variavel['imagem_banco'];

echo '<img src="'.$image.'" style="'.$style.'">';
?>
  • I appreciate trying to help but unfortunately your example is impractical within the source scope of my img tags since they come along with numerous other elements and not separately in a single string !

0

Try the following:

<?php
function removeEmptyImagesFromHtml($html) {
    $lastUseInternalErrors = libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    libxml_use_internal_errors($lastUseInternalErrors);

    $imgNodes = $dom->getElementsByTagName('img');
    $nodesToRemove = array();
    foreach($imgNodes as $imgNode) {
        if( !$imgNode->hasAttribute('src') || trim($imgNode->getAttribute('src')) === '' ) {
            $nodesToRemove []= $imgNode;
        }
    }
    foreach($nodesToRemove as $node) {
        $node->parentNode->removeChild($node);
    }
    return $dom->saveHTML();
}
ob_start('removeEmptyImagesFromHtml');
?>
<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <html>
        <img src="teste.png" />
        <img src="" />
        <img />
        <img src="ola.gif" />
    </html>
</html>
<?php
ob_end_flush();

The HTML output must be between the ob_start (that stores the HTML in memory, without passing to the browser) and the ob_end_flush (which sends the modified HTML to the browser).

  • Thanks for the example, but it doesn’t seem to have worked. I load content including two other pages (one pre-load and one load on demand) I had conflicts in assigning your example in hambas and trying to use only one for testing tbm seems not to have worked...not as expected. I added the code for a better purpose. Grateful.

  • Fixed an error: I was only removing the first image, maybe because I changed the DOM. I also put HTML to test. The output is: <!DOCTYPE html> <html><head><title></title></head><body><img src="test.png"><img src="ola.gif"></body></html> O ob_start('ob_gzhandler') before the ob_start('removeEmptyImagesFromHtml') will create problems. Put it later, do a function with both functions or configure it in Apache to compress output when the browser allows it (not enough, so watch your code - you have to validate it with HTTP headers).

Browser other questions tagged

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