Function To Generate Random String

Started on the old forum in December 2010 · view the original in the archive · old links redirect here

#algorithm #random #string #url-shortner

12 replies · 1,384 views · started 15 years ago · 1 min read

6 participants
ksg91 Developer · 162 posts #1

I was working on Url Shortner script and I needed a better algorithm that can generate a fixed length random string which have very less probability of collision with other strings in db. So I created one simple, yet efficient algorithm. I hope this is good. It returns you 8 character long random string.

<?php
//////////////////////////////////////
// Author: Kishan Gor a.k.a Ksg91
// Date: 27-12-2010
/////////////////////////////////////

//returns 8 character long random string
function getKSGRandomString()
{
  $a=array("0"=>"0","1"=>"1","2"=>"2","3"=>"3","4"=>"4","5"=>"5","6"=>"6","7"=>"7","8"=>"8","9"=>"9","10"=>"a","11"=>"b","12"=>"c","13"=>"d","14"=>"e","15"=>"f","16"=>"g","17"=>"h","18"=>"i","19"=>"j","20"=>"k","21"=>"l","22"=>"m","23"=>"n","24"=>"o","25"=>"p","26"=>"q","27"=>"r","28"=>"s","29"=>"t","30"=>"u","31"=>"v","32"=>"w","33"=>"x","34"=>"y","35"=>"z","36"=>"A","37"=>"B","38"=>"C","39"=>"D","40"=>"E","41"=>"F","42"=>"G","43"=>"H","44"=>"I","45"=>"J","46"=>"K","47"=>"L","48"=>"M","49"=>"N","50"=>"O","51"=>"P","52"=>"Q","53"=>"R","54"=>"S","55"=>"T","56"=>"U","57"=>"V","58"=>"W","59"=>"X","60"=>"Y","61"=>"Z");
  $rand1=mt_rand(00000000,99999999);
  $rand2=mt_rand(00000000,99999999);
  $string='';
  while($rand1>0)
  {
    $x = $rand1 % 100;
    $rand1=floor($rand1/100);
    $x = $x % 60; 
    $string.=$a[$x];
  }
  while($rand2>0)
  {
    $x = $rand2 % 100;
    $rand2=floor($rand2/100);
    $x = $x % 60; 
    $string.=$a[$x];
  }
  return $string;
}
?>

Expecting your advices and suggestions to improve it more. 🙂

Follow me @ksg91 | My Blog: http://ksg91.com | Nokia Blog: http://NokiaTips.in

frostymarvelous Senior · 266 posts #2

Won't this take too much time? I would have done something like this.

$x= 0; $string= ''; While($x <= $len ) { $v= rand(0,64); $string .= $a[$v]; $x ++; }

Nothing fancy. I'm mobile so pardon any errors, I'm just typing straight. And yes I know a for loop would be better. Hehe.

Perfection comes at a cost

I accept liberty!

razzbee Developer · 130 posts #3

Well i guess frost is correct but i will prefer this

<?php $rand1=rand(0,999); $rand2=rand(0,999); $rand3=rand(1,10); $rand_string=pow($rand1,$rand2); $rand_string=substr($rand_string,1,$rand3); sorry on mobile pardon me 4 the errors.
subzero Super moderator Fellow · 3,954 posts #4

lol

foreach('$a as $a');

Visit: Chat4u.mobi - The New Lay Of being a site of your dreams! Visit: WapMasterz Coming Back Soon!


SCRIPTS FOR SALE BY SUBZERO Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders. FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others... _______…

frostymarvelous Senior · 266 posts #5

I just noticed you tagged it url shortener, so performance won't be an issue to you. Rather, the uniqueness is important. Cool.

Perfection comes at a cost

I accept liberty!

Anshul Senior · 296 posts #6

you may try using mcrypt based encryption 🙂

metulj Super moderator Principal · 1,726 posts #7

does it have to be random string? is there any advantage of randomizing?

i mean, currently im also working on URL shortener script... but basicly i dont mind if it starts like

  • domaine.com/1
  • domaine.com/2
  • etc, etc
  • ...........
  • domaine.com/1359
  • etc...

im also trying to add option to create manual URL.. for example if i have some tralala.zip to link... it'll be domaine.com/tralala.zip <<== ofcourse if that name still available I.E. not yet in DB 🙂

It's better to keep your mouth shut and give the impression that you're stupid, than to open it and remove all doubt. ⓣⓗⓔ ⓠⓤⓘⓔⓣⓔⓡ ⓨⓞⓤ ⓑⓔ©ⓞⓜⓔ, ⓣⓗⓔ ⓜⓞⓡⓔ ⓨⓞⓤ ⓐⓡⓔ ⓐⓑⓛⓔ ⓣⓞ ⓗⓔⓐⓡ ! ιη тнєσяу, тнє ρяα¢тι¢є ιѕ α яєѕυℓт σƒ тнє тнєσяу, вυт ιη ρяα¢тι¢є ιѕ тнє σρρσѕιтє.

キノgんイノ刀g 4 ア乇ムc乇 ノ丂 レノズ乇 キucズノ刀g 4 √ノ尺gノ刀ノイリ!

frostymarvelous Senior · 266 posts #8

I don't think there's anything wrong with randomising but you should always check the Db to ensure it is unique.

Do something like yourls. Start with single char and then progress.

Perfection comes at a cost

I accept liberty!

ksg91 Developer · 162 posts #9

frostymarvelous wrote: Won't this take too much time? I would have done something like this.

$x= 0; $string= ''; While($x <= $len ) { $v= rand(0,64); $string .= $a[$v]; $x ++; }

Nothing fancy. I'm mobile so pardon any errors, I'm just typing straight. And yes I know a for loop would be better. Hehe.

actually, my algorithm was to convert an integer string into random character string. I was actually going to pass integer and get its string but then created like that. You have bit faster implementation of above function but algorithm is that get 16 digit integet, make pair of two integer and take modulo 60 (because we have 61 character in above array) and append it to string. 🙂

razzbee wrote: Well i guess frost is correct but i will prefer this

<?php $rand1=rand(0,999); $rand2=rand(0,999); $rand3=rand(1,10); $rand_string=pow($rand1,$rand2); $rand_string=substr($rand_string,1,$rand3); sorry on mobile pardon me 4 the errors.

can you explain this code?

subzero wrote: lol

foreach('$a as $a');

Didnt got what you wanted to post.

Anshul wrote: you may try using mcrypt based encryption :)

thanks. will check about that.

metulj wrote: does it have to be random string? is there any advantage of randomizing?

i mean, currently im also working on URL shortener script... but basicly i dont mind if it starts like

  • domaine.com/1
  • domaine.com/2
  • etc, etc
  • ...........
  • domaine.com/1359
  • etc...

im also trying to add option to create manual URL.. for example if i have some tralala.zip to link... it'll be domaine.com/tralala.zip <<== ofcourse if that name still available I.E. not yet in DB :)

Randomizing string has advantage of less guess/hit ratio. If its in sequence, one can guess any valid link. And some people wont like sharing their shorted link with everyone. And I am making it very basic, just wanted to make it for personal use but not limited to me only.

Follow me @ksg91 | My Blog: http://ksg91.com | Nokia Blog: http://NokiaTips.in

frostymarvelous Senior · 266 posts #10

I can't quote the whole post and I'm mobile but in reply to the reply you made to me. Wow. That must have involved some thinking right there. Mine was just off the bat. I. Saving this for future reference. Never knlw when it will come in handy. Either for use or for study.

Btw. I studied oop just by looking at ksg's code. He's that good.

Perfection comes at a cost

I accept liberty!

subzero Super moderator Fellow · 3,954 posts #11

using arry codes and trying to mix it in rand will not work so adding foreach a to arry code will give a random word single word.


Wont a htt(p)://domain.com/?9281

Use htaccess

Options +FollowSymLinks RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^?(.*)$ go.php?id=$1

Visit: Chat4u.mobi - The New Lay Of being a site of your dreams! Visit: WapMasterz Coming Back Soon!


SCRIPTS FOR SALE BY SUBZERO Chat4u Script : coding-talk.com/f28/chat4u-mobi-script-only-150-a-17677/ - > Best Script for your site no other can be hacked by sql or uploaders. FileShare Script : coding-talk.com/f28/file-wap-share-6596/ -> Uploader you will never regret buying yeah it mite be old now but it still seems to own others... _______…

ksg91 Developer · 162 posts #12

subzero wrote: using arry codes and trying to mix it in rand will not work so adding foreach a to arry code will give a random word single word.

how will it wont work? I still didnt get what you said about foreach a to array code.

Follow me @ksg91 | My Blog: http://ksg91.com | Nokia Blog: http://NokiaTips.in

Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close