note 128792 added to function.setcookie
| From: | silos at main dot php dot net | Date: | Sat, 12 Aug 2023 02:19:31 +0000 |
| Subject: | note 128792 added to function.setcookie | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220752@lists.php.net to get a copy of this message | ||
A cookie set using the "setcookie" function will be readable by the PHP script only after
refreshing the page. Sometimes, however, in certain specific situations, it is necessary to set a
cookie during the same page view, even before the page is reloaded. The only way to achieve this is
to set the cookie on the client side (that is, using JavaScript) and not on the server side (that
is, using PHP).
Here is example code:
<?php
//place this code between <head> and </head> tags
$cookie_name='example_cookie';
$cookie_value='example_value';
if(empty($_COOKIE['example_cookie']))
echo '<script type="text/javascript" >
var consent=confirm("Press \"OK\" to confirm or \"Cancel\" to
cancel...");
if(consent) document.cookie = "'.$cookie_name.'='.$cookie_value.';
expires=Wed, 05 Aug 9999 23:00:00 UTC";//in this line cookie is set through JavaScript
else
window.location.href="about:blank";
</script>';
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 178.235.147.10)
----
Manual Page -- https://php.net/manual/en/function.setcookie.php
Edit -- https://main.php.net/note/edit/128792
Del: integrated -- https://main.php.net/note/delete/128792/integrated
Del: useless -- https://main.php.net/note/delete/128792/useless
Del: bad code -- https://main.php.net/note/delete/128792/bad+code
Del: spam -- https://main.php.net/note/delete/128792/spam
Del: non-english -- https://main.php.net/note/delete/128792/non-english
Del: in docs -- https://main.php.net/note/delete/128792/in+docs
Del: other reasons-- https://main.php.net/note/delete/128792
Reject -- https://main.php.net/note/reject/128792
Search -- https://main.php.net/manage/user-notes.php