[英]PHP - writing into a file - fwrite
我是PHP菜鸟,但我正在尝试学习它。 我已经处理了一些变量并从html表单中获取了变量,我想采用用户在表单中键入的字符串-这是页面上表单的代码
<form method="POST" action="/php/write.php">
<input type="text" name="string"><input type="submit">
</form>
在子文件夹php中,我有文件“ write.php”,它看起来像这样
<?php
chmod(/write.txt, 0755);
$write == $_POST['string'];
$file = fopen("write.txt","w") or die("cant open file");
fwrite($file, $write);
fclose($file);
?>
我试图放入普通的HTML文件中,但也没有起作用。 问题是,当我键入表单并按Submit时,它将重定向我在write.php上,但没有任何反应,“ cant open file”未写入,也未出现任何错误,文件仍然为空,没有fwrite对我有用。 有人可以帮我吗?
您的代码有一些问题:
chmod(/write.txt, 0755);
文件名必须用引号引起来,并且它可能不应位于根目录中。 chmod()
函数仅适用于现有文件。 如果您的文件已经存在,这不是错误。
$write == $_POST['string'];
==
是比较运算符。 您要赋值=
。
你的代码应该是这个样子:
$write = $_POST['string'];
$file = fopen('write.txt','w') or die('cant open file');
fwrite($file, $write);
fclose($file);
chmod('write.txt', 0755);
(当我不需要在内部扩展变量时,我更喜欢用单引号引起来的字符串。)
另外 ,在编写良好的程序中,您应该:
isset ($_POST['string'])
检查$_POST['string']
在存在之前是否确实存在。 fopen()
, fwrite()
, fclose()
和chmod()
的返回值,并处理潜在的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.