Wordica
Wordica

Reputation: 2597

Cookie from JS vs Cookie in PHP

I do something like this:

JS:

Cookies.set(post_id + '_' + user_ip, post_id + "_" + user_ip, { expires: 1 });

PHP:

$cookie_str = $post_id.'_'.get_client_ip();
if (isset($_COOKIE[$cookie_str_]) ){
    print_r('ok exist');
}

But it doesn't work ... cookie exist I check in network in chrome developer tools. Is there some different between cookies in JS and PHP ? or I do some stupid mistake? IP is always that same ... console.log() form JS shows that same IP like PHP

ANSWER:

Ok I remove IP from cookie name and value and it start working: Cookie like : 54_23.23.211.2 was not visible by $_COOKIE[ ];

Now cookie is only a simple number of $post_id;

But why "54_23.23.211.2" doesn't work, I don't know... cookie like cookie = dots are not permitted ?

YES - http://harrybailey.com/2009/04/dots-arent-allowed-in-php-cookie-names/

Dots are not permitted in PHP cookies :)

Upvotes: 1

Views: 129

Answers (2)

YaBCK
YaBCK

Reputation: 3029

In my opinion i would go with using the post_id instead of post_id and user_ip

I recommend not using the IP address because there could be multiple machines behind the NAT routers sharing the one IP address, there will also be a the problem of mobiles always changing their IP address because they will also be connecting to different networks.

Please check this post I did for someone: https://stackoverflow.com/a/32758176/3296661

However if you want to stick with the method you've got try this:

Use str_replace() to strip all the dots from the IP address on PHP side and use split('.').join("") on JS side. This way both client and server side will match.

This is because dots are not permitted in PHP cookies.

JS:

user_ip = post_id.split('.').join("");
Cookies.set(post_id + '_' + user_ip, post_id + "_" + user_ip, { expires: 1 });

PHP:

$cookie_str = $post_id . str_replace(".","", get_client_ip());

if (isset($_COOKIE[$cookie_str_]) )
{
    print_r('ok exist');
}

Upvotes: 1

user5400659
user5400659

Reputation: 97

I dont know the source code of your Cookie object but expires: 1 looks like your cookie is set to expire one second later.

Upvotes: 0

Related Questions