Skip to content Skip to sidebar Skip to footer

How To Store Session Data Of User

first question for the site(i am new to this site) thought to post my most difficult problem ..... I have Login system in my site after successful login my protected page is displa

Solution 1:

You can write your login PHP like,

<?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();
    }
?>

Then to click on the URLs you could perhaps use jQuery and AJAX. You should declare a class like "link-block" in your CSS, and write the URLs like this

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

and add a click handler to those DIVs in the page's onReady Javascript, after including jQuery scripts:

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

The increase-point handler needs to open the session, which is the same code as you have above (so you can put it into an external include "session.php"), and open the database connection (another include...), then:

UPDATE usertable SETpoints= points + 1WHEREuser_id= {$_SESSION['user_id']};

or if you have a username only (ensure it's properly escaped)

...WHEREusername='{$escapedSessionUsername}';

By the way, I need to add the standard mysql_* deprecation disclaimer.

After which, you might return the current points to be displayed into a DIV with id of "points-block":

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

by returning it in JSON after querying them from the database (or you can keep them in session and update both DB and session; it saves you one query)

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

You can do this in other ways too, but I saw no anchor in your link div, so I guess you want something dynamic, which mostly means AJAX.

Post a Comment for "How To Store Session Data Of User"