Is it possible to set this cookie with js then access it later in the body with php? No matter where I put my script
when I echo with php it is always undefined until I refresh the page. I can put it in the head, above html, etc… doesn’t matter. What I want to be able to achieve is having that cookie set for use in my page – with php – without the refresh needed. Example case would be the initial page visit from a user on my site. The session.php is what starts the session.
test.php :
<?php
require $_SERVER['DOCUMENT_ROOT'].'/assets/functions/session.php';
?>
<!DOCTYPE html>
<html class="no-js" lang="en">
<!-- BEGIN HEAD -->
<head>
<script>
//returns browser timezone or defaults to UTC
var tz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
//store as cookie so you can use it with php
//document.cookie = "test_Timezone="+tz+"; expires=0; path=/; domain=test.com; secure; samesite=lax";
document.cookie = "test_Timezone="+tz+"; expires=0; path=/; domain=test.bs5; samesite=lax";
</script>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<body>
<?php
echo 'timezone is : '.$_COOKIE['test_Timezone'];
?>
</body>
<!-- END BODY -->
</html>
2
Answers
Server side code (PHP in your case) is executed before the client side script is executed; so you are attempting to retrieve cookie information that has not yet been stored.
You could either:
These are some creative ways that could resolve your issue.
The reason for this is that you have two actors here: the server and the client. It may happen to be the same machine while you work as a developer, but later on they may be two distinct, remote machines.
The flow is:
So your server will already have executed your PHP by the time your client is to execute your Javascript, independently of where you put your script textually. If you need to save a cookie and proceed with using it inside PHP, then you will need to send a request to your server. For this purpose you could test for
isset($_COOKIE['test_Timezone'])
and if it happens to be true, then display it. If it’s not true, then reload the page.