如果用户图片存在,则检查目录

时间:2017-04-10 19:36:32

标签: php file file-exists

我正在尝试执行以下操作

<?php 

echo '<img  style="margin-top:10px;" src="images/'.$_SESSION['username'].'.png" width="200px;" height="200px;">'; 

?>

但是我需要检查图像是否存在然后是否存在我回显用户名会话图像否则我回显另一张图片

1 个答案:

答案 0 :(得分:0)

以下是我如何解决它

    <?php 


    $rootPath = $_SERVER['DOCUMENT_ROOT'];
    $thisPath = dirname($_SERVER['PHP_SELF']);
    $onlyPath = str_replace($rootPath, '', $thisPath);
    $extension = ".png";
    $all =  $onlyPath.$_SESSION['username'].$extension;

if (file_exists($all)){

    echo '<img  style="margin-top:10px;" src="'.$onlyPath.$_SESSION['username'].'.png" width="200px;" height="200px;">';

} else {
  echo '<img  style="margin-top:10px;" src="usericon.png" width="200px;" height="200px;">';
}

    ?>

如何解决它的其他方法

<?php 

$user = $_SESSION ["username"];
$dir = 'images/'.$user.'.png';

if (file_exists($dir)) {
    //exists
} else {
   //not exists
}

?>
相关问题