我有一个Web表单,我想从用户那里获取数据并将其写入服务器上的文本文件,但是每次在表单中输入某些内容时,我都需要服务器创建一个具有随机名称的新文本文件。
到目前为止,我有这个,但是每次都不会做一个随机文件。
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$file = rand(0000,9999);
$ret = file_put_contents('/messages/$file.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
简单修复:
不能在单音符字符串('string'
)中替换变量,因此请使用双音符("string"
)。
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$file = rand(0000,9999);
// use double tics so that $file is inserted.
// like this: "/messages/$file.txt"
// alternatively, we could use: '/messages/' . $file . '.txt'
// (for those who are married to single tics)
$ret = file_put_contents("/messages/$file.txt", $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
?>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句