经过测试
更改此行
$fh = fopen($file, 'w');
至
$fh = fopen($myFile, 'w');
文件的变量不匹配。
您还可以使用以下内容进行错误检查。
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
和这个结合:
$fh = fopen($myFile, 'w') or die("Couldn't open file for writing!");
和
fwrite($fh, $stringData) or die("Couldn't write values to file!");
您可能还想添加一个if
条件来防止过早写入。
PHP 处理程序
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
if(isset($_POST['submit'])){
$myFile = "file.txt";
$fh = fopen($myFile, 'w') or die("Couldn't open file for writing!");
$stringData = "First\n";
fwrite($fh, $stringData) or die("Couldn't write values to file!");
$stringData = "Second\n";
fwrite($fh, $stringData) or die("Couldn't write values to file!");
fclose($fh);
if($fh) {
echo "Data successfully written to file.";
}
}
else {
echo "You cannot do that from here.";
}
?>
HTML 表单
(添加name="submit"
到提交按钮)
<form style="margin-top:70px;" align=center action="write.php" method="post">
<input type="submit" name="submit" value="Write"/>
</form>