如何存储用户的会话数据


How to Store session data of user

网站的第一个问题(我是这个网站的新手)想发布我最困难的问题.....

成功登录后,

我的站点中有登录系统,我的受保护页面仅在登录后显示,我想添加 $_SESSION['point'] 来存储用户的点,并将其保存到数据库中,如果用户单击链接,该点将增加。我想将这个增加的点存储到我的 userdb.php 中。我保留的所有注册信息。(我没有使用MySql进行注册表单我使用userdb.php文件)我受保护的页面php代码是

<?php
if (session_id() == "")
{
   session_start();
}
if (!isset($_SESSION['username']))
{
   header('Location: #');
   exit;
}
if (isset($_SESSION['expires_by']))
{
   $expires_by = intval($_SESSION['expires_by']);
   if (time() < $expires_by)
   {
      $_SESSION['expires_by'] = time() + intval($_SESSION['expires_timeout']);
   }
   else
   {
      unset($_SESSION['username']);
      unset($_SESSION['expires_by']);
      unset($_SESSION['expires_timeout']);
      header('Location: #');
      exit;
   }
}
if (session_id() == "")
{
   session_start();
}
if (session_id() == "")
{
   session_start();
}
?>

我的显示器.php显示网址

<?php
mysql_connect('Server', 'user', 'passs');
mysql_select_db('add');
$query =mysql_query('select * from addimage');
while( $row = mysql_fetch_assoc($query) )
{
echo ' 
<div style="min-width:300px;height:100px;border:red 5px;float:left;">'.$row['url']. '</div>';
}
?>

你可以这样写你的登录 PHP,

<?php
    // if PHP > 5.4: if (PHP_SESSION_NONE == session_status()) {
    if ('' == session_id()) {
        session_start();
    }
    if (isset($_SESSION['expires_by'])) {
        $expires_by = intval($_SESSION['expires_by']);
        if (time() < $expires_by) {
            $_SESSION['expires_by'] = time() + intval($_SESSION['expires_timeout']);
        } else {
            session_destroy();
        }
    }
    if (!isset($_SESSION['username'])) {
        Header('Location: ' . $_SERVER['REQUEST_URI']);
        exit();
    }
?>

然后要点击URL,你可以使用jQuery和AJAX。你应该在你的CSS中声明一个像"link-block"这样的类,并像这样编写URL。

echo '<div class="link-block">'.$row['url'].'</div>';

并在包含 jQuery 脚本后,在页面的 onReady Javascript 中向这些 DIV 添加一个点击处理程序:

$('.link-block').on('click', function(e) {
    $.post('/increase-points.php', { }, function(retval){
        if (retval.newpoints) {
            $('#point-block').html(retval.newpoints);
        }
    });
});

增加点处理程序需要打开会话,这与上面的代码相同(因此您可以将其放入外部包含"session.php"中),并打开数据库连接(另一个包含...),然后:

UPDATE usertable SET points = points + 1 WHERE user_id = {$_SESSION['user_id']};

或者,如果您只有用户名(确保它已正确转义)

...WHERE username = '{$escapedSessionUsername}';

顺便说一句,我需要添加标准的弃用免责声明mysql_*

之后,您可以将当前要显示的点返回到 ID 为 "points-block" 的 DIV 中:

    You have <span id="points-block"></span> points.

从数据库查询它们后将其返回为 JSON 格式(或者您可以将它们保留在会话中并更新数据库和会话;它为您节省了一个查询)

    // This in /update-points.php
    $retval = array('newpoints' => $updated_points);
    Header('Content-Type: application/json;charset=utf8');
    die(json_encode($retval));

您也可以通过其他方式执行此操作,但是我在您的链接div中没有看到锚点,所以我想您想要一些动态的东西,这主要意味着AJAX。