How to Generate Access Token in PHP

Created At: 2023-01-24 07:32:27 Updated At: 2023-08-19 06:32:05

Generating access token is easy in PHP, the only thing matters is that how secure is the token. There are many alogrithm that can generate secure code in PHP. 

What is access token?

It's token generated by your server, that's used to communicate between your app and server. With access token, app identifies with the server that, it's legit. Then we can use this access token to verify a lot of thing during communication.

In our case we will use some built in functions to do it. The functions are 

  1. rand()
  2. uniqid()
  3. md5()

The combination of these three functions will make a secured powerful access token. Let's take a look at them one by one and then we combine them together

rand()

It's a built in function that generates random number. It takes two parameters. First one is the minimum number and the second one is the maximum number.

We will generate random number that represent million

rand(1000000, 9999999);

That would generate a random number from 1000000 to 9999999. 

uniqid()

The above function generates an identifier. It's also unique but not 100% gauranteed. Let's see the an example.

<?php
// generating unique id
echo uniqid();
?>

It will have output like below

3b2c662647f18

In your case it should be different. It depends on your machine hardware clock.

Since uniqid() does not return gaurantee to return unique identifier, we can combine rand() and uniqid() together. 

We may combine them like below syntax

uniqid().rand(1000000, 9999999);

With the identifier we are connecting a random number. It should be pretty unique.

md5()

How to use MD5 in PHP? To calculate the MD5 hash of a string PHP has a pre-defined function md5(). The md5() function calculates the MD5 hash of a string input and returns the hash hexadecimal number. The md5() function uses the MD5 Message-Digest Algorithm.

Combine uniqid(), rand() and md5()

Combining all the above functions we may generate a secure token which would be used to communicate between app and server.

$access_token = md5(uniqid().rand(1000000, 9999999));

This token should be saved in the database. 

Now you should be able to use the access token for authentication. In next step you should be sending this token to your mobile app or web app and then save it there in the local storage. 

Next time you send a request to server, you may compare this token with the one saved in database.

Now, part of the code that I used generate token during login is here

    public function login(Request $request){

        $validator = Validator::make($request->all(),[
                'avatar'=>'required',
                'name'=>'required',
                'type'=>'required',
                'open_id'=>'required',
                'email'=>'max:50',
                'phone'=>'max:30'
        ]);
        if($validator->fails()){
            return ['code'=>-1, "data"=>"no valid data", 'msg'=>$validator->errors()->first()];
        }
        try{

        $validated = $validator->validated();
        $map = [];
        $map['type'] = $validated['type'];
        $map['open_id'] = $validated['open_id'];
        $result = DB::table('users')->select('avatar',
            'name',
            'description',
            'type',
            'token',
            'access_token',
            'online')
            ->where($map)->first();
        if(empty($result)){
            $validated['token'] = md5(uniqid().rand(10000, 99999));
            $validated['created_at'] = Carbon::now();
            $validated['access_token'] = md5(uniqid().rand(1000000, 9999999));
            $validated['expire_date'] = Carbon::now()->addDays(30);
            $user_id = DB::table('users')->insertGetId($validated);
            $user_result = DB::table('users')->select('avatar',
            'name',
            'description',
            'type',
            'token',
            'access_token',
            'online')->where('id', '=', $user_id)->first();

            return ['code'=>0, 'data'=>$user_result, 'msg'=>'User has been created'];
        }else{
            $access_token = md5(uniqid().rand(1000000, 9999999));
            $expire_date = Carbon::now()->addDays(30);
            DB::table("users")->where($map)->update(
                [
                    "access_token"=>$access_token,
                    "expire_date"=>$expire_date
                ]
            );
            $result->access_token= $access_token;
            return ['code'=>0, 'data'=>$result, 'msg'=>'User information updated'];
        }
        }catch(Exception $e){
            return ['code'=>-1, "data"=>"no data avilable", 'msg'=>(string)$e];
        }

    }

The above code was a part of Laravel and Front end application here. If you are interested you take the course on Udemy.

You may also take my Laravel(PHP) and Flutter course

Comment

Add Reviews