简体   繁体   中英

PHP & JQuery : Cookies in Real-Time

I am not too sure if this is possible which is why I am asking before I attempt it. The idea is to build a login file in PHP which when the credentials are correct, the $_COOKIE['fid'] is changed to a login key .

This file is going to be used using JQuery with a function $.post .

Is it possible to do a real-time cookie refresh in JQuery or PHP because the idea is that there is no response if the login is TRUE , the PHP code should pick-up that the cookie is now SET

PHP example:

if(isset($_COOKIE['fid'])):
   // do something
endif;

Or is this not possible because as soon as the page finishes loading, the if statements have already been returned true or false ?

I'd just love to be able to make some kind of background refresh which then the PHP code picks up and then does something so its all real-time.

Edit: I found this code to update it, but how would the PHP code know its been updated?

$('#login').click(function(){
     _gaq.push(['_trackEvent', 'viewerChose', $.cookie('whichSide')+'side']);
});

@MarcosPérezGude has explained in the Comments section that this isn't actually possible.

The only way to work with the update would to send it via AJAX methods and work with a response, however, this means the response has to be handled in JavaScript and not PHP .

Maybe one day they will make this possible haha.

Example of doing it the way that is possible -

JQuery:

$("#login-btn").click(function(){
    $("#login-load-icon").css("display") = "block";
    $.post( "example.php", { user: "example", pass: "example").done(function(data){
        if(data == 1){
            location.reload();
        } else {
            $("#login-error").css("display") = "block";
            $("#login-load-icon").css("display") = "none";
        }
    });
});

example.php:

if(isset($_POST['user']) && isset($_POST['pass'])):
    if(strtoupper($_POST['user']) == strtoupper("This would a Database Query")):
        if($_POST['pass'] == "This would you matching the hashed pass with the hash in the DB"):
            setcookie("fid", "LOGIN KEY HERE", time()+3600, "/");
        endif;
    endif;
endif;
// etc...

Then on the page you're in:

if(isset($_COOKIE['fid')):
        if($_COOKIE['fid'] == $Database['login_key']):
            // get all the user details and they're logged in
        else:
            // they tried to trick your system
    else:
        // load the login-btn
    endif;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM