【问题标题】:PHP not reading file?PHP不读取文件?
【发布时间】:2012-07-14 08:57:07
【问题描述】:

我不知道我到底哪里出错了。我已将问题缩小到 $file 没有被设置为任何东西,我不知道我哪里出错了。请帮忙:)

代码:($_GET['unit'] is 1)

                $filepathhalf = "http://sureclean.netai.net/data/";
                $date = date("Ymd");
                $unitnum = $_GET['unit'];
                $ext = ".txt";
                $filepath = $filepathhalf.$unitnum.$date.$ext;
                $bool = file_exists($filepath);
                if($bool = true)
                {
                    $fh = fopen($filepath, 'r');
                    $file = fread($fh, 4);
                    fclose($fh);
                }
                else{};
                $file = strval($file);
                echo $file;

你的网站/数据/120120714.txt:

true

【问题讨论】:

  • $bool = true 可能不是您想要的,赋值 (=) 与比较 (==) 不同。

标签: php fread


【解决方案1】:

file_exists

名为file_exists 的函数仅适用于本地文件,您无法通过此函数检查网络上的资源(通过HTTP)是否可用。

这与您在下面的 sn-p 中使用赋值而不是比较的事实一起提供了脚本的错误行为。

if($bool = true) 
  { ... }

打开

fopen 并不总是允许从外部源读取,但您确定这是必需的吗?如果您的文件确实是本地文件,请不要尝试通过网络阅读它,因为您可以通过更简单的方式访问它。


fread

fread 的第二个参数指定要读取的最大字节数,您当前已指定 4

目前您正尝试从$fh 中存储的文件句柄中读取 4 个字节,而您确实在读取这四个字节。

$file 将仅包含空格,因为这是存储在文件的前四个字节中的内容,如果您在问题中正确缩进了 yourwebsite/data/120120714.txt 的内容 - 也就是说。


如何一次读取整个文件?

PHP 提供了一个名为 file_get_contents 的函数,它将读取整个文件并将其作为字符串返回,但如果您真的在寻找一种使用 fread 读取文件的方法,您应该使用以下内容:

$file_data = fread ($fh, filesize ($filename));

【讨论】:

    【解决方案2】:

    if 条件下的矿工错误:

    if($bool == true)
    {
         // do the stuff
    }
    else{
         // also show some message here if file does not exists.
    }
    

    您可以使用其他一些函数来读取文件。比如:file('filename.txt');或 file_get_contents('filename.txt');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 2011-03-30
      相关资源
      最近更新 更多