Js does not set cookies

Hello everybody. I’m planning a movie review sharing social network (pophome.eu). I need to set a cookie for the session but lately it hasn’t been set and I don’t know why. The strange thing is that this morning everything was working, but now the cookie is not set when I register (or when I log in), so the index takes me back to login again because the following condition is true:

    		header("Location: login.php");

This is the code I use to set the session cookie:

    $length = 25;
    			 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    			 $charactersLength = strlen($characters);
    			 $randomString = '';
    			for ($i = 0; $i < $length; $i++) {
    			$randomString .= $characters[rand(0, $charactersLength - 1)];
                 var date = new Date();
                 var randomString = '<?php echo $randomString ?>';
                 document.cookie = "sessione=" + randomString + "; expires=" + date.toGMTString();

If anyone knows the reason for this strange mistake could you tell me? Thanks for your attention

For starters, there are a few things I would do differently:

  • If you want to use sessions, just use PHP sessions. That way, you don’t have to do any cookie management at all.
  • If you want to use cookies from PHP, then also write the cookies from PHP. You don’t need to use Javascript to create cookies. In fact, cookies that are only used from PHP should be set with the HttpOnly flag so they can’t be access from Javascript at all. That way, any malicious frontend code can’t tamper with the data.

For your issue specifically, you should first check in your browser whether the cookie is set. That should help narrow down whether the issue is in setting the cookie or reading it.


The cookie is not set because I have checked it from the browser. But at this point I’ll try to use php to insert cookies

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.