Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 271
Giffary Avatar asked Jun 15 '11 06:06

Giffary


People also ask

Does AJAX need cookies?

Basically, ajax request as well as synchronous request sends your document cookies automatically.

Can you set cookies with AJAX?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request. AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request.

How are cookies stored in PHP?

Cookies are always stored in the client. The path only sets restrictions to what remote pages can access said cookies. For example, if you set a cookie with the path "/foo/" then only pages in the directory "/foo/" and subdirectories of "/foo/" can read the cookie.


1 Answers

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, '/');
like image 109
Maxim Krizhanovsky Avatar answered Oct 21 '22 04:10

Maxim Krizhanovsky