初学者帮助:使用 PHP 创建和存储文本
我正在尝试编写一个程序,其基本思想是要求用户在文本区域中输入,然后将文本存储到单词文件中。这是我尝试使用的代码:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1>
<br>
<form method = "post"
action = "mysite.php">
<textarea name = "text"
rows = "10"
cols = "20">Write Here</textarea>
<input type = "submit"
value = "Submit Comment">
</form>
<?
if($_POST['text'] !== NULL){
$comment = $_POST['text'];
$file = fopen("texttest.txt", "a");
fputs($file, "<br>\n$comment");
fclose($file);
}
?>
</body>
</html>
我似乎无法让它正常工作。我也在考虑以某种方式使表单操作存储文本,然后重新加载网站,但我还没有让它工作(原始文件是 mysite.php,所以操作只是重新加载页面)。
如果有人对要使用的算法/不同的语法有更好的想法,请告诉我,因为我刚刚开始学习基本的 PHP 语法。
谢谢
I'm trying to write a program where the basic idea is I ask the user for input in a textarea, and then the text gets stored into a word file. Here is the code I'm trying to use:
<html>
<head>
<title>Simple Guestbook</title>
</head>
<body>
<h1>Simple Guestbook Comment Creator</h1>
<br>
<form method = "post"
action = "mysite.php">
<textarea name = "text"
rows = "10"
cols = "20">Write Here</textarea>
<input type = "submit"
value = "Submit Comment">
</form>
<?
if($_POST['text'] !== NULL){
$comment = $_POST['text'];
$file = fopen("texttest.txt", "a");
fputs($file, "<br>\n$comment");
fclose($file);
}
?>
</body>
</html>
I can't seem to get this to work properly. I was also thinking about somehow making the form action store the text and then reload the site, but I haven't gotten that to work (the original file is mysite.php, so the action is to just reload the page).
If anyone has any better ideas of an algorithm to use/different syntax to use, please let me know, as I just started learning basic PHP syntax.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查以下内容:
无论如何,当某些东西不起作用并且您想知道导致错误的原因时,请将
error_reporting(-1);
放在 php 的开头 - 它将输出任何错误或警告,包括那些被警告的错误或警告通过 fopen()。另外,您可能想检查变量是否已正确提交:分配变量后立即
echo $comment
。Check the following:
Anyway, when something does not work and you want to know what's causing the arror, place
error_reporting(-1);
at the beginning of your php - it will output any error or warning, including the ones trown by fopen().Also, you might want to check whether the variable has been correctly submitted:
echo $comment
right after you assign it.像这样的东西可能会起作用。
您可能想对他们输入的值等进行更多操作,但这基本上可以满足您的要求。
您还需要确保您拥有尝试写入的文件的正确路径,并且该文件具有允许写入的正确权限:
此外,由于您要返回同一页面,您可能需要添加某种消息,让对方知道他们已成功将某些内容输入到您的地址簿中。
Something like this might work.
You might want to do more with the values they are entering and all, but this will basically do what you are asking.
You will also want to make sure that you have the correct path of the file you are trying to write to and that that file has the correct permissions to allow it to be written to:
Also, since you are returning to the same page you may want to put some kind of message letting the person know that they succeeded in entering something into your address book.