如何在php中创建一个带.txt扩展名的随机文件名?

时间:2014-03-04 23:44:05

标签: php

我有一个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');
}

?>

3 个答案:

答案 0 :(得分:2)

简单修复:

变量不会替换为单一字符串'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');
}

?>

答案 1 :(得分:1)

使用substr和str_shuffle函数可以创建一个随机文件名,如下所示。

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

答案 2 :(得分:0)

您可以使用php函数microtime()

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