我正在尝试使用 php 和 html 写入文件,我在我的计算机上运行 XAMPP 本地服务器我写了一些我在 YouTube 上在线找到的 html 和 php 代码,我也在 Mac 上只是为了让人们知道。
这是我的 html:
<html>
<head>
<title>testinf file I/O</title>
</head>
<body>
<form action="data.php" method="post">name:
<input type="text" name="name">
address:<textarea name="adress"></textarea>
email: <input type="email" name="email">
<input type = "submit"name="btnl">
</form>
</body>
</html>
这是我的 PHP:
<html>
<head>
<title>store data to file
</title>
</head>
<body>
<?php
$name=$_POST['name'];
$address=$_POST['address'];
$email=$_POST['email'];
$str="name is".$name."address is".$address."email is".$email;
$fp=fopen("B.txt","w");
fwrite($fp,$str);
fclose($fp);
echo"conctent is stored in the B.txt file";
?>
</body>
</html>
当我运行服务器并转到本地主机时,转到 html 页面并填写表格并单击提交我然后尝试查找包含我在论坛上输入的内容的 txt 文件,但我找不到它。然后我查看了日志并在访问日志中找到了这个:
::1 - - [10/Apr/2023:11:59:59 -0400] "POST /testingI:O/data.php HTTP/1.1" 500 88
我在 PHP_error_log 中发现了这个:
[10-Apr-2023 17:59:59 Europe/Berlin] PHP Warning: Undefined array key "address" in /Applications/XAMPP/xamppfiles/htdocs/testingI:O/data.php on line 9
[10-Apr-2023 17:59:59 Europe/Berlin] PHP Warning: fopen(B.txt): Failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/testingI:O/data.php on line 13
[10-Apr-2023 17:59:59 Europe/Berlin] PHP Fatal error: Uncaught TypeError: fwrite(): Argument #1 ($stream) must be of type resource, bool given in /Applications/XAMPP/xamppfiles/htdocs/testingI:O/data.php:14
Stack trace:
#0 /Applications/XAMPP/xamppfiles/htdocs/testingI:O/data.php(14): fwrite(false, 'name isfwiweijf...')
#1 {main}
thrown in /Applications/XAMPP/xamppfiles/htdocs/testingI:O/data.php on line 14
如果有人能帮我解决这个错误,因为我一直在尝试写入一个文件,但它只是没有解决。
我查看了多个 YouTube 视频,他们不断获取 txt 输出文件,这些文件将在 php 和 html 代码所在的同一 htdocs 文件夹中弹出。
如果您尝试使用 fopen 函数打开您没有写入权限的文件,它将返回 false。并且由于您试图在不检查此返回的情况下使用 fwrite 函数写入文件,因此您导致了致命错误。尝试以下解决方案来解决此脚本中的问题。
解决方案:
在 PHP 中从 POST 检索数据时,注意名称很重要。您必须在 PHP 中以相同的方式输入地址输入的名称。要解决此问题,请按如下方式编辑 PHP 中的相关行:
$address = $_POST['adress'];
此外,在尝试检索 $_POST 中包含的数据之前,使用 isset 函数检查它是否存在很重要。例如
if (isset($_POST['adress'])) {
$address = $_POST['adress'];
}
...
确保在对文件系统执行任何操作时拥有必要的权限。您需要为文件夹启用写入权限:
/应用程序/XAMPP/xamppfiles/htdocs/testingI:O/
这个过程可以针对不同的操作系统以不同的方式完成。对于 Mac,你需要研究它是如何完成的。
使用file_put_contents函数代替fopen、fwrite、fclose函数,简化文件写入过程。 这个函数等同于依次调用fopen()、fwrite()和fclose()将数据写入文件。
file_put_contents('B.txt', $str);