Skip to content

Commit c6b73d3

Browse files
committed
Update function random_string
1 parent 03dcde8 commit c6b73d3

File tree

1 file changed

+53
-14
lines changed

1 file changed

+53
-14
lines changed

system/helpers/string_helper.php

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -198,42 +198,81 @@ function reduce_multiples($str, $character = ',', $trim = FALSE)
198198
/**
199199
* Create a "Random" String
200200
*
201-
* @param string type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, encrypt and sha1
202-
* @param int number of characters
203-
* @return string
201+
* Function update by FuelPHP
202+
*
203+
* @param string $type type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, encrypt and sha1
204+
* @param int $length number of characters
205+
* @return string the random string
204206
*/
205-
function random_string($type = 'alnum', $len = 8)
207+
function random_string($type = 'alnum', $length = 16)
206208
{
207-
switch ($type)
208-
{
209+
switch ($type) {
209210
case 'basic':
210211
return mt_rand();
212+
break;
213+
214+
default:
211215
case 'alnum':
212216
case 'numeric':
213217
case 'nozero':
214218
case 'alpha':
215-
switch ($type)
216-
{
219+
case 'distinct':
220+
case 'hexdec':
221+
switch ($type) {
217222
case 'alpha':
218223
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
219224
break;
225+
226+
default:
220227
case 'alnum':
221228
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
222229
break;
230+
223231
case 'numeric':
224232
$pool = '0123456789';
225233
break;
234+
226235
case 'nozero':
227236
$pool = '123456789';
228237
break;
238+
239+
case 'distinct':
240+
$pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
241+
break;
242+
243+
case 'hexdec':
244+
$pool = '0123456789abcdef';
245+
break;
229246
}
230-
return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
231-
case 'unique': // todo: remove in 3.1+
247+
248+
$str = '';
249+
for ($i = 0; $i < $length; $i++) {
250+
$str .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
251+
}
252+
253+
return $str;
254+
break;
255+
232256
case 'md5':
233-
return md5(uniqid(mt_rand()));
234-
case 'encrypt': // todo: remove in 3.1+
235-
case 'sha1':
236-
return sha1(uniqid(mt_rand(), TRUE));
257+
case 'unique':
258+
return md5(uniqid(mt_rand(), true));
259+
break;
260+
261+
case 'sha1' :
262+
return sha1(uniqid(mt_rand(), true));
263+
break;
264+
265+
case 'uuid':
266+
$pool = array('8', '9', 'a', 'b');
267+
268+
return sprintf('%s-%s-4%s-%s%s-%s',
269+
random_string('hexdec', 8),
270+
random_string('hexdec', 4),
271+
random_string('hexdec', 3),
272+
$pool[array_rand($pool)],
273+
random_string('hexdec', 3),
274+
random_string('hexdec', 12));
275+
break;
237276
}
238277
}
239278
}

0 commit comments

Comments
 (0)