dsolwotv00116 2014-03-04 15:44
浏览 57
已采纳

如何在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');
}

?>
  • 写回答

3条回答 默认 最新

  • douhuike3199 2014-03-04 15:51
    关注

    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');
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部