A commonly repeated advice over the web is not to store usernames in cookies.
However, I don't really understand the problem. What I'm doing in my web application is: I generate a 16-byte (converted to 32-bit hex) random session ID generated from a CSPRNG, and store the username and this session ID in cookies.
Needless to say is the fact that the existence of the session ID and its correlation with the user is checked from a database before performing any actions in the web application. I'm doing this to speed up the database access a bit, and to protect against the problem of collisions, where an user may find themselves authorized as a different user due to an accidental collision.
What is the weakness in this scheme?
bin2hex(random_bytes(16)), but there may be a small chance of collisions (entropy in the pool running low, mere chance, among others) and that's not something I can fix. – May 21 '16 at 04:28random_bytesis cryptographically secure. As you are getting 128 bits, the odds of a collision are effectively zero. – Neil Smithline May 21 '16 at 20:04