Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following function, that generates, stores in a session variable and returns a token (anti-CSRF):
PHP
function generateToken() {
  $_SESSION["token"] = bin2hex(random_bytes(32));
  return $_SESSION["token"];
}

I could make it easier:
PHP
function generateToken() {
  return $_SESSION["token"] = bin2hex(random_bytes(32));
}

It works. But is assignment while returning a good practice? Are there shortcomings/downsides with it?

What I have tried:

PHP
function generateToken() {
  return $_SESSION["token"] = bin2hex(random_bytes(32));
}
Posted
Updated 27-Apr-23 22:54pm
Comments
Member 15627495 28-Apr-23 4:49am    
Hello !

the 'try' looks better than the other.

one thing is about what is $_SESSION for the server : it's a global Var.
you can access this var at every time in all your php script.

it makes the 'return' useless,

sure it's kind of overload, php permit 'recursion' ( allocating a value in a var , then return it. )

it works, it pass , well done !

using '$_session["token"] when needed is equal.
LB2371 28-Apr-23 6:00am    
The reason of "return" is in the way I use the function:
form
...
input type="hidden" name="token" value="?=generateToken()?"
...
/form
Member 15627495 28-Apr-23 6:27am    
yes, this way every form is 'single' and the '$_SESSION' integrates security strings.

every loading pages will refresh $_SESSION['token'] and will have a 'numberized/crypted' key.

good job !

1 solution

There is no real difference as far as execution is concerned - but it's a little harder to read as a single line of code, so I'd go with the separate assignment.

It's also a lot easier to debug with separate instructions, when you need to!
 
Share this answer
 
Comments
Member 15627495 28-Apr-23 8:12am    
it's 'getter' and 'setter' by the same function too, as a 'Class' can do

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900