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

3

I am making a system where the user can post images, texts, etc ... however in the system every image posted must be uploaded to the server and the user can delete them.

With the deletion of the image from the server, the posts that contain such an image have the 404 error.

I know that it is possible to show a default image for images not found via .htaccess but what I want is not to show neither standard error nor image, I just do not show img .

The system is structured like this:

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
}
?>
    
asked by anonymous 07.10.2014 / 01:37

3 answers

5

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

You can also put in your CSS so that images with the src empty attribute are not displayed, eg:

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

JSFiddle

If your database is written to the image with the img tag, one solution would be to HTML parse with PHP and get src , then test if the image exists, eg

$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 transparent 1x1 pixel png image, eg

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule \.(gif|jpe?g|png|bmp) ../img/invisivel.png [NC,L]
    
07.10.2014 / 02:35
0

Create a blank default image and check to see if src of the image has something, if it does not, put the image in white.

<?php

$imagem = $variavel['imagem_do_banco'];

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

Or try to put a hidden in style of tag <img>

<?php

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

echo '<img src="'.$image.'" style="'.$style.'">';
?>
    
07.10.2014 / 03:25
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 output of HTML should be between ob_start (which stores the HTML in memory, without going to the browser) and ob_end_flush (which sends the changed HTML to the browser).

    
07.10.2014 / 22:51