如何使用 php 检查会话是否已设置

how to check whether session is set or not using php

我想将访问者的 IP 信息插入我的 mysql table,我正在使用 jQuery Post 方法来做到这一点。 这是我的代码

Main_page.php

<?php
if(!isset($_SESSION['v_Id']) || empty($_SESSION['v_Id'])) {
echo '<script>
    $.get("https://ipapi.co/json", function (response) {
    /*
    var ip = response.ip,
        country = response.country_name,
        isp = response.org,
        timezone = response.timezone,
        calling_code = response.country_calling_code
        language = response.languages;
    alert(ip);
    alert(country);
    alert(isp);
    alert(language);
    alert(calling_code);
    alert(timezone);
    */
    $.post("./saveData", {
            ip: response.ip,
            country: response.country_name,
            isp: response.org,
            timezone: response.timezone,
            calling_code: response.country_calling_code,
            language: response.languages
        }, function(data, status){
        console.log("Data: " + data + "\nStatus: " + status);
    });
});
</script>';
}
?>

saveData.php

<?php
include 'config.php';
$date  = date('Y-m-d H:i:s', time());
// from my assets class to generate a unique string
$Id = $assets->randomString(15, 1, "upper_case,numbers");
$id = $Id[0];
$form_id = filter_var($_POST['form_id'], FILTER_SANITIZE_STRING);
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$ip = filter_var($_POST['ip'], FILTER_SANITIZE_STRING);
$country = filter_var($_POST['country'], FILTER_SANITIZE_STRING);
$isp = filter_var($_POST['isp'], FILTER_SANITIZE_STRING);
$calling_code = filter_var($_POST['calling_code'], FILTER_SANITIZE_STRING);
$timezone = filter_var($_POST['timezone'], FILTER_SANITIZE_STRING);
$t_ins = $conn->prepare("INSERT INTO visits(ip, country, isp, calling_code, timezone, time, visit_id) VALUES(?, ?, ?, ?, ?, ?, ?)");
$t_ins->bind_param("sssssss", $ip, $country, $isp, $calling_code, $timezone, $date, $id);
if($t_ins->execute()){
    $_SESSION["v_Id"] = $id;
}
?>

我的 PHP 代码运行良好,但每次刷新 Main_page.php 时,js 代码仍在执行,即使 Session 是设置。

您缺少 session_start(); header。您应该先启动 session。