【问题标题】:Mac PHP can't write to .log fileMac PHP 无法写入 .log 文件
【发布时间】:2021-10-11 01:56:18
【问题描述】:

我尝试在我的 Mac 上托管一个简单的网站。我的目标是制作一个每个人都可以输入文本的表单,然后这段文本将显示在 HTML 主页中。我遇到了两个问题:

  • 当我运行 php submit.php 时,我可以在 mylog.log 中看到更新,但在使用浏览器 (Safari) 并访问网站本身时却看不到。

  • 即使我设法写入文件,我也不知道如何让 HTML 与之交互以显示内容。

这是index.html中的代码:

<form action="submit.php" method="post" target="_self">
  <input type="text" id="textform2" name="msg">
  <input type="submit">
</form>

还有submit.php

<!DOCTYPE html>

<html>
  <head>
    <title>Processing</title>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
<?php
$message = 'hi';
$file = 'mylog.log';
$handle = fopen($file, 'w');
fwrite($handle, $message);
fclose($handle);
?>
    <p class="par">Our server is processing your request. You will be redirected…</p>
    <script> location.replace("http://johann.local"); </script>
  </body>
</html>
  • 我把这些文件放在Macintosh/Library/WebServer/Documents

  • 不需要消毒,因为它只会托管在我的私人 WiFi 网络上。

【问题讨论】:

  • 您使用哪个网络服务器?您可以尝试在 Documents 目录下运行php -S localhost:5000,然后尝试转到localhost:5000
  • 效果很好!太感谢了。 (我的第二个问题仍然需要帮助)
  • 没问题 :) 。而且,我不明白你的第二个问题。你能再解释一下吗?谢谢
  • 假设我在mylog.log 中有文本“我爱PHP”。如何将 HTML 元素的内容设置为“我爱 PHP”?

标签: php html macos


【解决方案1】:

首先,您需要运行 PHP Web Server 以使您的 submit.php 正常工作。 使用 index.html 和 submit.php 转到您的目录,然后运行:

php -S localhost:5000

那么你的网站就可以在 http://localhost:5000 访问了。

关于你的第二个问题,如果你想轻松写入文件,可以使用file_put_contents函数代替fopen/fwrite/fclose,反之亦然,你可以通过file_get_contents轻松读取内容。

这是使用示例:

<!DOCTYPE html>

<html>
  <head>
    <title>Processing</title>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
<?php
$message = 'hi';
$file = 'mylog.log';
file_put_contents($file, $message); // save $message into $file
?>
    <p class="par">Our server is processing your request. You will be redirected…</p>
    <p>Contents of the log: <?php echo file_get_contents($file); ?></p>
  </body>
</html>

(我删除了重定向以查看内容) 使用 echo 功能结合 file_get_contents,您可以将日志文件的内容打印到 HTML 中。

【讨论】:

  • 谢谢,但这并没有解决我的问题。我仍然在日志文件中看不到任何内容。
  • @JohannLau 请检查我编辑的答案,如果正确请接受。谢谢
  • 是否也可以使用 Javascript 执行 echo file_get_contents($file); 部分?我想将结果放在index.html 主页面中。
  • Javascript 帮不了你。如果要将其放入 index.html,则需要将其重命名为 index.php,然后将 file_get_contents 用作 susual
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 2011-08-16
  • 2017-06-28
  • 2012-10-16
  • 1970-01-01
相关资源
最近更新 更多