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']); } }
session_startand using global variables like$_SESSION? If you are using that, delete that code instantly when using Laravel... Please, do read the documentation as you are very confused, it will help you a lot (always READ the documentation, specially from a Framework): laravel.com/docs/10.x/sessioncredentials: "include"set. developer.mozilla.org/en-US/docs/Web/API/…: "Controls whether or not the browser sends credentials with the request, as well as whether any Set-Cookie response headers are respected."