如何在php中使用.txt扩展创建随机文件名?

I have a web form and i want to get the data from the user and write it to a text file on the server but i need the server to create a new text file with a random name each time something is entered into the form.

So far i have this but it wont make a random file each time.

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "
";
$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');
}

?>

Simple fix:

Variables are not replaced in single-tic strings ('string'), so use double tics ("string").

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "
";
    $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');
}

?>

You can use the php function microtime()

$file = microtime().".txt";
$ret = file_put_contents('/messages/'.$file, $data, FILE_APPEND | LOCK_EX);

Using the substr and str_shuffle functions you can create a random file name like the following.

$filename = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6) . '.txt';
if ( !file_exists($filename) ) {
   //File put contents stuff here
}