php - 如何以 php 形式将输入的数据保存到文本文件(if 语句)
问题描述
我正在为我的代码苦苦挣扎,因为它比让表单将其数据保存到文本文件有点复杂。我希望表单显示有条件的消息,例如如果提交了一个空表单,"please enter comment"
则会显示,如果输入完成,它将显示数据已被接受并"congratulations"
会出现。如果是其他任何数据,它只会说数据已收到并"thank you for the comment"
会出现。我能够做到这一点,但由于某种原因,我无法将 php 文件中的输入数据保存到文本文件中。这是我的代码:
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset ="UTF-8">
<title>mission_2-02</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="comment" placeholder="comment">
<input type="submit" name="submit">
</form>
<?php
$str = $comment . PHP_EOL;
$filename="mission_2-02.txt";
$fp = fopen($filename,"w");
$comment = $_POST ["comment"];
if ($comment==""){echo "";}
else echo $comment . "is accepted <br>";
if (empty ($comment)) {echo"please enter comment";}
elseif ($comment=="finished"){echo "congratulations";}
elseif (!empty($comment)){echo "thank you for the comment";}
else{fwrite($fp, $str );echo $str ;fclose($fp);}
if (file_exists($filename)){
$lines = file($filename,FILE_IGNORE_NEW_LINES);
foreach ($lines as $line){
echo $line . "<br>";
}
}
?>
</body>
</html>
解决方案
一个主题的变化也许......
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset='UTF-8' />
<title>mission_2-02</title>
</head>
<body>
<form method='post'>
<input type='text' name='comment' placeholder='comment' />
<input type='submit' />
</form>
<?php
$filename='mission_2-02.txt';
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST["comment"] ) ){
$output=array();
$errors=array();
$comment=filter_input( INPUT_POST, 'comment', FILTER_SANITIZE_STRING );
if( !empty( $comment ) )$output[]=sprintf('Thankyou - your comment "%s" was accepted!', $comment );
else $errors[]='Please enter a comment!';
if( strtolower( trim( $comment ) )==='finished' )$errors[]='Congratulations';
if( !empty( $errors ) )printf('<pre>%s</pre>',implode( PHP_EOL, $errors ));
else{
file_put_contents( $filename, $comment . PHP_EOL, FILE_APPEND );
printf('<pre>%s</pre>',implode( PHP_EOL, $output ) );
}
}
if( file_exists( $filename ) ){
foreach( file( $filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ) as $line )printf('%s<br />',$line);
}
clearstatcache();
?>
</body>
</html>
推荐阅读
- c# - ServiceFabric 与本地 WPF 应用程序的通信
- discord.py - 有没有办法取消挂起的 bot.wait_for?
- python - 如何在类中实现 list() 支持
- c# - 如何遍历文本框并清除它们?
- c++ - C++ game engine scripting can't load variables
- haproxy - PFSense 2.5 问题上的 HA 代理
- postgresql - 在 PostgresSQL 中如何编写返回多行和多列的查询
- c++ - C ++读入第一项,检查,然后读入其余项目
- javascript - 打字稿:嵌套模板对象中的数组值
- c - 我的 C 代码中的内存泄漏在哪里导致我收到分段错误