【问题标题】:PHP write file writes constants twicePHP写入文件两次写入常量
【发布时间】:2014-09-05 08:11:43
【问题描述】:

当我尝试执行这个非常简单的代码时

<?php
  $myfile = fopen("db.txt", "at") or die ("Unable to open file!");
  $text = $_GET["name"];
  $text .="\n";
  echo $text;

  fwrite($myfile, $text);
  fwrite($myfile, "abc\n");
  fclose($myfile);
?>

我的文件变成了这样的东西

coolname
abc
abc

“abc\n”字符串的两倍。我保证,我的代码只有那么几行。

请求只是http://localhost:8080/helloworld.php?name=coolname

但如果我只使用这个...

  fwrite($myfile, $_GET["name"]);

一切正常,但我想要一个结束行。

谁能解释一下为什么会这样?

我正在使用 PHP AppEngine SDK。 (距离我上次使用 PHP 已有 9 年了)

解决方案:

问题是,当我在浏览器中打开这个 URL 时,它被处理了两次,做了一些奇怪的事情,我不知道为什么,但是我的应用只需要从自定义应用中调用,所以,从我的应用中,这段代码只执行一次。不是真正的解决方案,错误仍然存​​在,但不会影响我的工作流程。

【问题讨论】:

  • 你的文件的初始内容是什么,$_GET['name'] 的内容以及“一切正常”时的输出?
  • localhost:8080/helloworld.php?name=coolname 当不写任何东西时,输出只是'coolname'。 (没有空格或结束线或简单的字符或其他)
  • 如果你尝试怎么办:fwrite($myfile, $text . "abc\n");
  • 一个wreider的东西:coolname\nabc\n\nabc\n为什么中间有两个“\n”?哈哈
  • 你用“a”打开文件,这意味着你将追加到已经存在的内容的末尾。

标签: php google-app-engine


【解决方案1】:

您正在使用fwrite($myfile, "abc\n"); 写入 abc。是你 $_GET 还包含 abc 否则写得很好。

<?php 

  $myfile = fopen("YourFile.txt", "at") or die ("Unable to open file!");
  $text = 'hello guys';
  $text .="\n";
  echo $text;

  fwrite($myfile, $text);
  fwrite($myfile, "abc\n");
  fclose($myfile);
?>

【讨论】:

  • 不,我的 $_GET 不包含“abc\n”字符串,这就是我输的原因。请求是这个localhost:8080/helloworld.php?name=coolname
  • 在 fwrite($myfile, $text); 之后关闭文件然后再次打开然后使用 fwrite($myfile, "abc\n");看看会发生什么。
  • 一个wreider的东西(和Cleément的建议完全一样):coolname\nabc\n\nabc\n中间两个“\n”
  • 以 mode=a 即 fopen("YourFile.txt", "a") 打开文件并尝试。
  • 相同 :( 感谢您的努力 可能是 AppEngine SDK 的错误?
猜你喜欢
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多