提问人:Jeremy Crête 提问时间:4/11/2023 最后编辑:BarmarJeremy Crête 更新时间:4/11/2023 访问量:220
尝试使用 PHP 写入文件
trying to write to a file with php
问:
我正在尝试使用 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);
评论
/Applications/XAMPP/xamppfiles/htdocs/testingI:O/
B.txt
a
undefined array key
adress
address
file_put_contents("B.txt", $str);