我有一个回呼用户名并将其插入img src的脚本。只要图像在目录中,这个方法就能很好地工作。如果文件存在,我如何创建一个if语句,它只回显下面的命令?如果不存在则显示default.png
我试过使用mod_rewrite,但没有任何运气。
<div class="contactphoto"><img src="contactphoto/<? echo ($note['user_name'] == "Support")? $note['first_name'].''.$note['last_name'] : $note['user_name'];?>.png"/></div>
名称说明了一切:file_exists()
我想这就是你想要的。
<?php
$file = ($note['user_name'] == "Support") ? $note['first_name'].''.$note['last_name'] : $note['user_name'];
$file .= '.png';
if(!file_exists($_SERVER{'DOCUMENT_ROOT'} .'/'.$file)){
$file = 'placeholder.png';
}
?>
<div class="contactphoto">
<img src="contactphoto/<?php echo $file; ?>"/>
</div>
如果失败,尝试一个测试(这应该匹配图像的路径),还要注意大小写敏感性:
echo $_SERVER{'DOCUMENT_ROOT'} .'/'.$file;