Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

jquery - cookies problem in PHP and AJAX

I face some problem on my script that I use PHP and jquery to create login system.

First I have PHP page contain form for login. when user click submit I use jquery to send data to server

$.post('server_login.php', {username:username.val(), password:password.val()}, function(data){
    alert(data);
}); 

in server_login.php I have function to doing login user.

if($_POST['username']=='username' && $_POST['password']=='1234'){
    $expire = time() + 60*60*24*30; //1 month expired.
    setcookie("user_id", $_POST['username'], $expire);
    echo true;
}

and jquery alert "1" on my login page.

the problem is when i refresh my website and retieve cookie, it not show me.

print_r($_COOKIE);

anything wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the script you are calling is located in another folder on the server (or via url rewrite it appears as if it is under another path), make sure to set the path parameter of the cookie.

By default, setcookie() sets the cookie only for the current path.

If your page is www.domain.com and you make ajax call to www.domain.com/auth/login.php the cookie will be set to /auth and will not be available outside /auth.

So try changing to this:

setcookie("user_id", $_POST['username'], $expire, '/');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...