[英]How do I rename a filename to a random filename in PHP?
I have a .php file with a random name. 我有一个带有随机名称的.php文件。 And I want to rename it to something another random name when a specific button was hit. 我想在按下特定按钮时将其重命名为另一个随机名称。
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
if (isset($_SESSION['submit'])) {
rename(, generateRandomString())
}
I have this code here and I think that I did everything right, but I don't know how to do the rename function 我在这里有这段代码,我认为我做对了所有事情,但是我不知道如何执行重命名功能
you need to look up the rename() function in the PHP docs: http://php.net/manual/en/function.rename.php 您需要在PHP文档中查找named()函数: http : //php.net/manual/en/function.rename.php
if (isset($_SESSION['submit'])) {
$oldFileName = 'foo.txt';
$newFileName = generateRandomString() . '.txt';
rename($oldFileName, $newFileName);
}
This is it in its basic form, but in production you would want to handle errors and store the new filename etc. 这是其基本形式,但是在生产中,您将需要处理错误并存储新文件名等。
To improve the function . 改善功能 。
This shuffles an array with the letters/numbers and take the ten first characters. 这将使用字母/数字对数组进行混洗,并获取前十个字符。
This should be more efficient than looping. 这应该比循环更有效。
$characters = array ('0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
);
shuffle($characters);
return implode("", array_slice($characters, 0,10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.