テスト済み
この行を変更
$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>