文件已存在?显示图像否则显示默认图像

Dou*_*leA 0 php webpage

我似乎无法使用以下代码?

$playerfileLocation = "../wp-content/gallery/playerphotos/' . $playerid . '.jpg";
if(file_exits($playerfileLocation)) 
echo "The file File exists";
else
echo "The file File does not exist";
Run Code Online (Sandbox Code Playgroud)

"playerid"字段是一个可以通过的数字.

我似乎无法让它工作.Urgh!

Vir*_*dra 5

您的报价不匹配.试试这个代码.

$playerfileLocation = "../wp-content/gallery/playerphotos/" . $playerid . ".jpg";
if(file_exists($playerfileLocation)) 
echo "The file File exists";
else
echo "The file File does not exist";
Run Code Online (Sandbox Code Playgroud)

更新:实际上我建议使用下面的代码,因为每当PHP看到双引号时,它会尝试解析它之间的任何内容,在这种情况下不需要.这是性能的一个小优化.

$playerfileLocation = '../wp-content/gallery/playerphotos/' . $playerid . '.jpg';
if(file_exists($playerfileLocation)) 
echo "The file File exists";
else
echo "The file File does not exist";
Run Code Online (Sandbox Code Playgroud)

另外,要检查文件是否存在,如果不显示默认图像,请使用以下代码:

$playerfileLocation = '../wp-content/gallery/playerphotos/' . $playerid . '.jpg';
$defaultfileLocation = '../wp-content/gallery/playerphotos/default.jpg';
if (!file_exists($playerfileLocation)) {
    $playerfileLocation = $defaultfileLocation;
}
Run Code Online (Sandbox Code Playgroud)