【问题标题】:Simple test for file_exist failsfile_exist 的简单测试失败
【发布时间】:2020-10-29 00:49:46
【问题描述】:

最简单的测试代码:-

<?php
if (file_exists('https://mywebsite/testarea/test.html')) {
    echo 'File exists';
} else {
    echo 'Not found';
}   
?>

我从本地主机 (wamp) 运行此测试。为什么这找不到文件?我已经仔细检查过它是否存在于指定的路径中。请帮忙。

【问题讨论】:

  • 提示 从 PHP 5.0.0 开始,这个函数也可以与一些 URL 包装器一起使用。请参阅支持的协议和包装器以确定哪些包装器支持 stat() 系列功能。

标签: php file-exists


【解决方案1】:

您传递的文件 url 托管在远程服务器上的其他地方而不是您的计算机上,这就是它无法找到它的原因。

如果你的 localhost 文件夹或计算机上 wamp 具有读取权限的任何地方有相同的文件,它将顺利通过检查。

但是,如果你想检查一个特定的 url 是否存在,那么你可能想看看 get_headers 函数:

$headers = get_headers('https://mywebsite/testarea/test.html');

if($headers && strpos($headers[0], 200)) {
    echo 'URL exists';
} else {
    echo 'URL does not exist';
}

【讨论】:

  • 我的错,感谢@B001ᛦ 指出。我已经纠正了:-)
【解决方案2】:

您需要使用文件或目录的路径。请参阅 file_exists 手册:https://www.php.net/manual/en/function.file-exists.php 对于文件函数包装器支持:https://www.php.net/manual/en/wrappers.php

对于您的情况

<?php
 if (file_exists('./testarea/test.html')) {
  echo 'File exists';
  } else {
 echo 'Not found';
 }   
?>

在 Windows 上,使用 //computername/share/filename 或 \computername\share\filename 检查网络共享上的文件。

【讨论】:

    【解决方案3】:

    file_exists() 检查文件或目录是否存在于运行脚本的同一系统中。

    <?php
       $filename = '/path/to/foo.txt';
    
       if (file_exists($filename)) {
          echo "The file $filename exists";
       } else {
          echo "The file $filename does not exist";
       }
    ?>
    

    如果您通过 http 在远程位置查找文件而不是使用 get_header()

    <?php
       $url = 'https://mywebsite/testarea/test.html';
       $array = get_headers($url);
       $string = $array[0];
       if(strpos($string,"200")) {
          echo 'url exists';
       } else {
          echo 'url does not exist';
       }
    ?>
    

    【讨论】:

      【解决方案4】:

      你可以使用file_get_contents()

      if (file_get_contents('https://mywebsite/testarea/test.html')) {
          echo 'File exists';
      } else {
          echo 'Not found';
      }
      

      或者只是在How to check if a file exists from a url的帮助下构建了这个

      $ch = curl_init('https://mywebsite/testarea/test.html');
      curl_setopt($ch, CURLOPT_NOBODY, true);
      curl_exec($ch);
      $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      
      if ($code == 200) {
          echo 'File exists';
      } else {
          echo 'Not found';
      }
      

      【讨论】:

      • 感谢大家的帮助。明天将有另一个 gp 使用给出的建议。
      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多