3

I am working on a Yii app that requires the 'users' table to have a column 'token' that will need to be a unique random string that is based upon that user in the table (eg there will never be the same token twice).

Can anyone give me some tips on doing this, or are there a Yii component/extension/generator already setup to do this.

Also - what is the most optimised db column type for this?

Zabs
  • 13,852
  • 45
  • 173
  • 297

2 Answers2

3

I like to use CSecurityManager with generateRandomString() for this. Be aware that it generates a string which does contain the chars ~ and _

DB column would be a varchar with a length of your string length.

chris---
  • 1,536
  • 1
  • 13
  • 14
  • that sounds like good, does this prevent any clashes? e.g if I have a table with a 2 million rows, would I get 2 million unique 'random strings'? – Zabs Aug 18 '14 at 10:31
  • No these are not unique. You have to check this manually and create a new string if there is already the same in the db. – chris--- Aug 18 '14 at 10:57
  • Thanks - this is a really good function! Once we upgrade to a later version of Yii we'll use this – Zabs Aug 18 '14 at 11:20
0

I suggest just to use hash, that produces long string and use some very unique string to be hashed:

sha512($userName.time().rand(1000, 9999));

Some PHP hash algorithms lengths

Community
  • 1
  • 1
Justinas
  • 41,402
  • 5
  • 66
  • 96