Welcome Guest, Not a member yet? Register   Sign In
Is random_string() function generate unique string?
#1

I'm using random_string() to generate 8 letters long unique string. My question is: will CI create UNIQUE random string each time?
Reply
#2

No, because CI does not know how many other strings have already been generated.  It has nothing to compare against.

Your code must test for a unique value (perhaps using a database lookup) and ask for a new random_string() until you are given a string which does not exist in your database.

Note this from the CI 3.0 docs
Quote:Usage of the unique and encrypt types is DEPRECATED. They are just aliases for md5 and sha1 respectively.
CI 3.1 Kubuntu 19.04 Apache 5.x  Mysql 5.x PHP 5.x PHP 7.x
Remember: Obfuscation is a bad thing.
Clarity is desirable over Brevity every time.
Reply
#3

(02-01-2015, 06:40 PM)twpmarketing Wrote: No, because CI does not know how many other strings have already been generated.  It has nothing to compare against.

Your code must test for a unique value (perhaps using a database lookup) and ask for a new random_string() until you are given a string which does not exist in your database.

Note this from the CI 3.0 docs

Quote:Usage of the unique and encrypt types is DEPRECATED. They are just aliases for md5 and sha1 respectively.

Actually, it uses uniqid(), which should produce strings that are unique per machine. The problem is, the uniqid() output goes through a sha1() call where collisions become possible, even if only in theory.

But otherwise - yes, the function is deprecated and should not be used.
Reply
#4

Use This code for random string.
public function genRandomString() {
$length = 20;
$characters = "O123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz~*^";
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[rand(0, strlen($characters))];
}
return $string;
}
Reply
#5

(02-02-2015, 01:43 AM)bblluuss Wrote: Use This code for random string.
public function genRandomString() {
       $length = 20;
       $characters = "O123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz~*^";
       $string = '';
       for ($p = 0; $p < $length; $p++) {
           $string .= $characters[rand(0, strlen($characters))];
       }
       return $string;
   }

There's nothing random about it. Read this: http://blog.astrumfutura.com/2013/03/pre...you-think/

Also, the topic is about unique strings, not random ones.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB