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

Php check in dir if user picture exists

我正在尝试执行以下操作

<?php 

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

?>

但我需要检查图片是否存在,如果存在,我回显用户名会话图像,否则我回显另一张有脸的图片

我是这样解决的

    <?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
}

?>