【问题标题】:file_exists in PHP [duplicate]文件存在于 PHP [重复]
【发布时间】:2012-03-17 06:47:35
【问题描述】:

可能重复:
How can one check to see if a remote file exists using PHP?
Check if file exists on remote machine

我在处理这段代码时遇到了问题。我正在尝试在下面的$url 中搜索文件,并且该文件确实存在,但代码正在返回No files located here。我要么语法错误,要么无法以这种方式搜索文件。

请帮忙。提前致谢。

<?php

function formaction()
{

$url = "http://".$_SERVER['HTTP_HOST'] . "/" . basename(dirname (dirname (dirname (dirname
(__FILE__))))) . "/process.php"; 

$path = false;

      if (@file_exists($url))
      {
         $path = $url;
      }

else
      {
          echo "No file located here";
      }


return $path;

}

echo formaction();


?>

【问题讨论】:

  • file_exists() 不适用于 URL
  • 嗨 Pekka,有没有办法以正确的方式调用文件,然后将该路径转换为上述 URL?任何指导都会有帮助。我只需要将其转换为 URL,因为当我将其插入表单 action="" 时,其他方式将无法正确呈现。例如,当我这样调用时,浏览器会变得混乱...../home2/fortehome/richmindonline/testenvironment...
  • 请不要使用@ 来抑制错误。这是一种非常草率和懒惰的做法。
  • 是的,这是从另一个帖子中复制的。我什至不知道那是什么……哈哈。但我会删除。

标签: php


【解决方案1】:

由于 file_exists() 不适用于 url:

你可以使用get_headers()来检查它的404或者不直接去这个sn-p:

取自 PHP 手册:http://www.php.net/manual/en/function.file-exists.php#85246

function url_exists($url) {
    // Version 4.x supported
    $handle   = curl_init($url);
    if (false === $handle)
    {
        return false;
    }
    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
    curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox    
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);   
    return $connectable;
}

但在这种情况下,它发现您不习惯从 URL 中查找.. 而是查找本地脚本。您不应使用 URL,而应使用实际的绝对或相对路径。

检查:

echo getcwd() . "\n";

另外,检查 dirname(),您将能够通过这种方式确定相对/绝对路径。

【讨论】:

  • 我非常关心这段代码,因为只有一行记录为// this works。我怎么知道其他线路有效???
猜你喜欢
  • 1970-01-01
  • 2011-04-11
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 2020-05-23
  • 1970-01-01
  • 2020-08-19
相关资源
最近更新 更多