/    Sign up×
Community /Pin to ProfileBookmark

Random Token Generation

Hello community, I’m fairly new to PHP, so any guidance is pretty much appreciated. Currently I’m trying to implement a login page. I started to think that identity authentication (email + pass) wasn’t good enough to prevent someone from accessing pages that require user to login (by directly accessing the script file). For example, adding posts, managing users, etc.

And as far as I’m concerned, this goes through my mind:

session_start();
class Token{

private $upper = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
private $lower = “abcdefghijklmnopqrstuvwxyz”;
private $num = “0123456789”;
private $alphaLen = 26;
private $numLen = 10;

private $key;

function __construct(){
for($i = 0; $i < 10; $i++){
$x = rand(0, 2);
switch($x){
case 0:
$r = rand(0, $this->alphaLen);
$this->key .= $this->upper{$r};
break;

case 1:
$r = rand(0, $this->alphaLen);
$this->key .= $this->lower{$r};
break;

case 2:
$r = rand(0, $this->numLen);
$this->key .= $this->numLen{$r};

}
}

}

function getKey(){
return $this->key;
}

}

$t = new Token();
$token = $t->getKey();

$_SESSION[‘auth’] = $token;
setcookie(‘token’, $token, 0);

//Below is code for other PHP script
session_start();
if(!isset($_COOKIE[‘token’]) && !isset($_SESSION[‘auth’]){
echo ‘Hotlinking’;
} else if($_COOKIE[‘token’] != $_SESSION[‘auth’]){
echo ‘Hotlinking’;
} else {
echo ‘good’
//script goes here
}

Is this acceptable in term of security? Or perhaps is there any better way to do so?

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogAug 19.2018 — Rather than doing all that work, I'd just do something like:
``<i>
</i>$token = sha1(uniqid(null, true));<i>
</i>
`</CODE>
E.g.:
<CODE>
`<i>
</i>15:29 $ php -a
Interactive shell

php &gt; $token = sha1(uniqid(null, true));
php &gt; echo $token;
9f627e0076d8042ffa3de6f6f93265d778a177fa
php &gt; $token = sha1(uniqid(null, true));
php &gt; echo $token;
3ba0657f00dcbed6eb66140e88f385b38a7bbbdd<i>
</i>
``
×

Success!

Help @mc_connor spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...