好的,这是我的镜头。
/*first of all, you should always check if posted vars are actually set
and not empty. for that, you can use an universal function "empty", which
checks if the variable is set / not null / not an empty string / not 0.
In such way you will avoid PHP warnings, when some of these variables
will not be set*/
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$saywords = !empty($_POST['saywords']) ? : $_POST['saywords'] : '';;
$mail = !empty($_POST['mail']) ? $_POST['mail'] : '';
/*Secondly, do not use \n, \r, \r\n, because these are platform specific.
Use PHP_EOL constant, it will do the job perfectly, by choosing
what type of line-break to use best.
As others mentioned - in your scenario, the string would be better solution.
Add everything into string, and then put its contents into file. Avoid using
double quotes, when you define PHP strings, and use single quotes instead - for
performance and cleaner code.
*/
$data = 'Name: '.$name.PHP_EOL.'E-Mail: '.$mail.PHP_EOL.'Message: '.$saywords.PHP_EOL.PHP_EOL;
file_put_contents($t.$ip.'.txt', $data); // Will put the text to file
顺便说一句,我强烈建议在将数据保存到该 txt 文件之前还添加一些额外的验证。使用此代码,某人可以通过无限制地发布大量数据来轻松弄乱您的 txt 文件的内容。
提示:
1) 只接受长度和字符有限的名称(不允许使用特殊符号或换行符 - 您也可以在保存之前将它们过滤掉)
2) 验证已输入的电子邮件 - 如果格式正确,电子邮件地址的域是否存在 mx 记录,等等...
3) 接受长度有限的“saywords”,如果需要 - 拒绝或过滤掉特殊字符。
通过这种方式,您将获得更清晰的提交。