尝试转发到文本文件时出错


Errors when I try to fwrite to a textfile

我正在尝试制作一个独特的命中计数器。我从网上"借用"了一些代码,但就是无法使用。(顺便说一句,我是一个自学成才的新手。)即使有这里人的帮助,我也无法让它发挥作用。因此,我从头开始编写自己的代码,重新学习"f"语句。我现在有了它,它将读取文本文件中的所有ip地址,并将每个地址与用户的ip进行比较,如果已经输入,则退出循环。

现在我正在尝试打开计数文件,读取一个条目,将其递增一,然后将其写回文件。但它就是不起作用。我在这里找到了更多的帖子,并尝试了他们建议的内容,比如"cmod"命令和所有可能的数字,但什么都没有。然后我发现了如何打开更好的错误报告。(以前有建议,但我不知道怎么做。)现在我遇到了一堆错误,我"认为"服务器上有什么东西不允许我写入文件。这是我正在使用的代码,仅用于增量部分:

ini_set('display_errors', 'On');
error_reporting(E_ALL);
//  read contents of count.txt
$handle = fopen($count_file, "r");
$old_count=fgets($handle);
echo "Old count = " . $old_count . "<br><br>"; 
fclose($handle);
//  write contents of count.txt
chmod($count_file, 0777);
$fp = fopen($count_file, 'ab');
if (false === $fp) {
    throw new RuntimeException('Unable to open log file for writing');
}
$handle = fopen($count_file, "w");  
$new_count = $old_count +1;
echo "New count = " . $new_count;
fwrite($handle, $new_count);
fclose($handle);

旧计数和新计数显示正常,但新计数无法写入txt文件。以下是现在显示的错误消息:

警告:chmod()[function.chmod]:在第50行的/home/users/tecitout/counter/fullarray1.php中不允许操作

警告:fopen(count.txt)[function.fopen]:无法打开流:在第51行的/home/users/tecitout/counter/fullarray1.php中权限被拒绝

致命错误:未捕获异常"RuntimeException",消息为"无法打开日志文件进行写入",位于/home/users/tecitout/counter/fullarray1.php:53堆栈跟踪:#0{main}在第53行的/home/uusers/tecitout/counter/fullarray1.php中抛出

我真的不明白这些错误。这是我好友的服务器出了问题吗?还是我写代码太差了。我非常感谢你的帮助。

如果你想写入一个文件,你需要对它拥有写入权限。此外,要对文件进行chmod,你需要拥有它,或者以root身份登录。

所以你的错误信息,按顺序:

Warning: chmod() [function.chmod]: Operation not permitted in /home/users/tecitout/counter/fullarray1.php on line 50

对应于CCD_ 1。php运行的用户似乎并不拥有该文件。

Warning: fopen(count.txt) [function.fopen]: failed to open stream: Permission denied in /home/users/tecitout/counter/fullarray1.php on line 51

这对应于$fp = fopen($count_file, 'ab');,意味着该文件不可写,因为chmod不起作用。

Fatal error: Uncaught exception 'RuntimeException' with message 'Unable to open log file for writing' in /home/users/tecitout/counter/fullarray1.php:53 Stack trace: #0 {main} thrown in /home/users/tecitout/counter/fullarray1.php on line 53

是由于if (false === $fp)并且是预期的。

删除count.txt,只要Web服务器有权写入要放置count.txt的目录,就可以执行以下操作:

$c = 0;
$count_file = 'count.txt';
if(file_exists($count_file)) {
    $c = (int)file_get_contents($count_file);
    echo "Old count = $c<br><br>";
}
file_put_contents($count_file, $c++);
echo "New count = $c<br><br>";

先生,谢谢您的帮助。我把所有的文件都复制到了我租的网络空间,并取得了成功。不幸的是,AbraCadaver提供的令人印象深刻的代码读取并增加了文件中的数字,但它既没有写入新数字,也没有给我任何错误。然而,我在上面写的脚本不好的代码实际上可以在我的服务器上运行。整个问题实际上是服务器上的权限。至少在我把头发都拔出来之前我得到了帮助!