Authorization on the site via VK

Hi, I’m new to php, so I’m writing code for my site via ChatGPT, please don’t judge me for this.
I am trying to create authorization via VK on my site, but for some reason when a new user tries to log in, he is simply redirected to the original page (index.php ), without even adding the user to the database, but when I try to log in, everything works correctly and my user_id and token are successfully added to the database, please tell me what I’m doing wrong, and correct my mistakes if possible, since I can’t figure out what’s wrong in the code for the second day.
Here is my code:

<?php
$uid = $_GET['uid'];
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
$photo = $_GET['photo'];

$servername = "localhost";
$username = "---";
$password = "---";
$dbname = "---";


$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql_check_user = "SELECT * FROM access_tokens WHERE user_id = '$uid'";
$result_check_user = $conn->query($sql_check_user);

if ($result_check_user->num_rows > 0) {
    $row = $result_check_user->fetch_assoc();
    $token = $row['token'];
    $expiration = $row['expiration'];

    if (strtotime($expiration) > time()) {
        session_start();
        $_SESSION['first_name'] = $first_name;
        $_SESSION['last_name'] = $last_name;
        header("Location: index.php");
        exit();
    } else {
        $token = bin2hex(random_bytes(16));
        $expiration = date('Y-m-d H:i:s', strtotime('+30 days'));

        $sql_update_token = "UPDATE access_tokens SET token = '$token', expiration = '$expiration' WHERE user_id = '$uid'";
        if ($conn->query($sql_update_token) === TRUE) {
            echo "Token updated successfully<br>";
        } else {
            echo "Error updating token: " . $conn->error;
        }
    }
} else {
    $token = bin2hex(random_bytes(16));
    $expiration = date('Y-m-d H:i:s', strtotime('+30 days'));

    $sql_insert_user = "INSERT INTO access_tokens (user_id, token, expiration) VALUES ('$uid', '$token', '$expiration')";

    if ($conn->query($sql_insert_user) === TRUE) {
        session_start();
        $_SESSION['first_name'] = $first_name;
        $_SESSION['last_name'] = $last_name;
        header("Location: index.php");
        exit();
    } else {
        echo "Error creating new user: " . $conn->error;
    }
}

$conn->close();
?>
Sponsor our Newsletter | Privacy Policy | Terms of Service