当我在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);
?>
所有文件都在同一目录中,但文本文件中没有任何内容。怎么了?
提前致谢!
答案 0 :(得分:1)
<强>测试强>
更改此行
$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
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>