当在HTML中按下按钮时,我试图简单地将一些文本写入.txt文件(在Mac上)。这是我尝试过的:
.HTML:
<form style="margin-top:70px;" align=center action="write.php" method="post">
<input type="submit" value="Write"/>
</form>
.PHP:
<?php
$myFile = "file.txt";
$fh = fopen($file, 'w');
$stringData = "First'n";
fwrite($fh, $stringData);
$stringData = "Second'n";
fwrite($fh, $stringData);
fclose($fh);
?>
所有文件都位于同一目录中,但文本文件中不显示任何内容。怎么了?
提前感谢!
已测试
更改此行
$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.";
}
?>
网页表单
(在提交按钮中添加name="submit"
)
<form style="margin-top:70px;" align=center action="write.php" method="post">
<input type="submit" name="submit" value="Write"/>
</form>