-1

当在 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);
?>

所有文件都在同一个目录中,但文本文件中没有任何内容。怎么了?

提前致谢!

4

1 回答 1

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 处理程序

<?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>
于 2013-10-15T19:44:28.590 回答