【问题标题】:PHP File exists not working?PHP文件存在不起作用?
【发布时间】:2011-11-01 09:13:53
【问题描述】:

我想检查一个页面是否存在。我的文件是 article.php 。文章的网址是 article.php?id=1 article.php?id=2 等等。但是当我这样检查时它不起作用:

$filecheck = "article.php?id=$id";
if (file_exists($filecheck)) {
echo "This article exists.";
} else {
echo "Sorry this article does not exist.";
}

但它总是返回“对不起,这篇文章不存在”。 我该如何解决这个问题?

【问题讨论】:

  • 为什么要将 query_string 添加到您的 $filecheck var 中?
  • 除非你指定一个完整的protocol://host/path/file类型的url,否则所有的文件函数都会假设你正在执行一个本地文件操作,并且你的代码正在寻找一个字面名称为article.php?id=XXX的文件,它不太可能存在。

标签: php file exists


【解决方案1】:

不要将查询字符串传递给它。

$filecheck = 'article.php';

【讨论】:

  • 如果我的回复解决了您的问题,请考虑接受它作为您问题的答案。
【解决方案2】:

文件“article.php?id=$id”将不存在,因为它不是物理文件。

我假设您正在使用 $id 来查找数据库中存在的文章。如果是这种情况,那么 file_exists 函数就不是您所需要的。

您需要做的是编写一个快速的 MySQL 语句来检查文章是否存在,然后从那里开始。

可能是这样的:

$query = "SELECT * FROM articles WHERE id='$id'";
$result = mysql_query($query);

// Check if result is there (ie article exists)
if ($result) {
    echo "This article exists.";
} else {
    echo "Sorry this article does not exist.";
}

我希望这会有所帮助。如果您还需要什么,请告诉我。

【讨论】:

  • 没有问题,很高兴它对你有用。如果您对答案感到满意,请考虑接受它作为答案。
  • 看来他并不在乎:)
【解决方案3】:

因为没有文件叫:article.php?id=$id

可能有一个文件名为:article.php :)

【讨论】:

    【解决方案4】:

    如果它们是物理页面而不是动态创建的内容,请使用这种方式:

    $filecheck = "article_1.php"
    
    if (file_exists($filecheck)) {
    echo "This article exists.";
    } else {
    echo "Sorry this article does not exist.";
    }
    

    否则检查ID是否在DB中。

    【讨论】:

    • 好建议!我会检查它是否在数据库中。谢谢! :)
    【解决方案5】:

    它没有找到文件的原因是因为你有一个查询字符串。如果您偶然从其他来源获取此数据并且无法控制是否随它一起发送查询字符串,那么您可以这样做:

    $yourFile = 'article.php?id=$id'; // Or wherever you get this value from
    $yourFile = strstr( $yourFile , '?' , TRUE );
    
    echo $yourFile; // now has a value of article.php
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      相关资源
      最近更新 更多