【问题标题】:File Exists? Display image else display default image文件已存在?显示图像否则显示默认图像
【发布时间】:2012-01-27 04:49:15
【问题描述】:

我似乎无法让以下代码工作?

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

“playerid”字段是一个被传递的数字。

我似乎无法让它工作。呃!

【问题讨论】:

  • 这个相对路径有效吗?
  • 否...页面在到达 if 语句后停止。我在此“测试”下方有未显示的文本。

标签: php webpage


【解决方案1】:

您的引号不匹配。试试这个代码。

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

更新: 实际上我建议使用下面的代码,因为每当 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";

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

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

【讨论】:

  • 中的双引号有什么问题,当 PHP 看到双引号时,它会尝试解析它之间的任何内容,这在这种情况下不是必需的。这是性能上的一个小优化。
  • 当 PHP 看到双引号时,它会尝试解析它,这需要一些时间(虽然很少,但仍然需要一些时间)。如果您使用单引号,则 PHP 不需要解析它,从而节省解析它所需的时间。在这种情况下,字符串中没有变量,因此不需要解析它,除非你这样做 $playerfileLocation = "../wp-content/gallery/playerphotos/$playerid.jpg"; 这将需要 PHP 解析整个字符串。此外,代码现在不是很可读。
  • 我终于弄清楚了问题它与我使用的路径有关。我需要定义一个绝对路径: $absolutepath = $_SERVER{'DOCUMENT_ROOT'}.'wp-content/gallery/playerphotos/' 。 $照片名。 '.jpg'; file_exists 函数现在可以正常工作。 ;)
【解决方案2】:

您的代码拼写错误:(exist not exits)

$playerfileLocation = "../wp-content/gallery/playerphotos/$playerid.jpg";

$default_player = "../wp-content/gallery/playerphotos/default.jpg";

if(file_exits($playerfileLocation)) 

{

}

else

{

$playerfileLocation=$default_player;

}

【讨论】:

  • 现在我觉得自己像个白痴。谢谢你解决了我的问题。
【解决方案3】:

在 php 中,我们也可以在双引号中获取变量值。在路径中使用双引号是一种很好的做法,因此不需要太多缩进。

$playerfileLocation = "../wp-content/gallery/playerphotos/$playerid.jpg";


$default_player = "../wp-content/gallery/playerphotos/default.jpg";
if(!file_exists($playerfileLocation)) 
{
$playerfileLocation=$default_player;
}

【讨论】:

    猜你喜欢
    • 2012-07-23
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2012-01-31
    • 2018-05-07
    • 2011-11-01
    • 2019-06-13
    相关资源
    最近更新 更多