【问题标题】:file_exists not working with localhost URLfile_exists 不适用于 localhost URL
【发布时间】:2015-05-09 23:34:36
【问题描述】:

我在 PHP 中有这段代码:

if (file_exists($_POST['current_folder'])) {
    //do something
} 

但是file_exists 总是返回假。传递给函数的值是:

echo $_POST['current_folder']);  //This prints: http://localhost/wordpress/wp-content/music

我还尝试使用本地主机上的不同文件夹。该函数始终返回 false。

我也试过is_dir()。但即使是这个函数,上面的 URL 也会返回 false。

Stack Overflow 上有很多相关的问题。但他们中的大多数人建议file_exists 仅适用于相对 URL。但是从this link 可以看出http:// URL 也被file_exists 函数支持。

我错过了什么?

【问题讨论】:

  • 使用本地文件路径,而不是网络路径

标签: php file-exists


【解决方案1】:

使用目录路径;不是网址:

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
   echo "The file $filename exists";
} else {
   echo "The file $filename does not exist";
}
?>

【讨论】:

  • 好的,谢谢您的回答。有没有办法检查php中是否存在远程目录?
  • 我也试过 is_dir() 。但即使它不适用于 http url
  • 无法检查远程目录是否存在。这不安全
【解决方案2】:

使用 Apache 2.4.9 在 windows 下测试。

<?PHP
$crl = curl_init("http://localhost/symfony2/");
curl_setopt($crl, CURLOPT_NOBODY, true);
curl_exec($crl);

$ret = curl_getinfo($crl, CURLINFO_HTTP_CODE);
curl_close($crl);

if ($ret == 200)
    echo 'File exists';
else
    echo 'File does not exist';
?>

它有效,只是一个注释,由于某种原因它需要尾部斜杠。

代码200 表示OK(成功)。

【讨论】:

    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 2019-05-22
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2017-06-06
    • 2015-12-13
    相关资源
    最近更新 更多