phplaravelsession-variables

PHP Session Variable Issue


I have a project which is react js and laravel php.I have two apis, one generate_otp an second verify_otp. Now the generate_otp works and stores the otp in session. I tested it by returning the value and its good but the issue is when I make a call to verify_otp, the session variable does not have a value. Returning the session variable from verify_opt sometimes give error like 500 internal server error and 'otp' key error which is the session variable. Later I added credentials:'include' in frontend hoping it solves it but now it returns a completly different value something like 466782 which is not the correct value and it returns the exact same value everytime. By the way everything works on postman but not in browser. Code below.

FRONTEND:

export const generateOTP = async () => {
 const response = await fetch(`http://localhost:8080/generate_otp`, {
  method: "GET",
  headers: { "content-type": "application/json" },
   });
};

export const verifyOTP = async (otp) => {
 const response = await fetch(`http://localhost:8080/verify_otp`, {
  method: "POST",
  body: otp,
  credentials: "include",
 });
 console.log(await response.json());
};

BACKEND:

$router->post('verify_otp', 'ContactController@verify_otp');
$router->get('generate_otp', 'ContactController@generate_otp');

public function generate_otp(){
    session_start();
    $otp = random_int(100000, 999999); 
    $_SESSION['otp'] = $otp;
    return $_SESSION['otp'];
}

public function verify_otp(Request $request){
    session_start();
    if($_SESSION['otp'] === $request){
        return response()->json(['success'=>1,'message'=>'OTP has been verified']);
    }else{
        return response()->json(['success'=>1,'message'=>'Please enter the correct OTP code']);
    }
}

Solution

  • This is not the correct way of doing it with react js as it requires a REST API if you are running react js on a different port and Laravel on a different port. Your Session is not maintained that's why every time you called an API and call a second API the session is not accessed which you saved in the previous request. So for a reason, you can have 2 methods to perform your this task. In the case of Postman, it maintains a session that's why your code is working with the Postman.

    Method 1

    Make a table called otp_verify which will have at least these columns id, otp and expires_on. Whenever you send OTP save that OTP into the otp_verify table with expires_on let's say 15 min so store current time + 15 mins. In the first request after storing that OTP in the database return response with the id of that row that has just been inserted. In the second request pass that id to the server with OTP and then check with id if that id exists and has not expired. then match the OTP and respond accordingly.

    Method 2

    You can run your build file with Laravel and have the same host so that your session is maintained.