gpt4 book ai didi

javascript - 使用此 javascript 和 php cookie 代码时遇到问题

转载 作者:行者123 更新时间:2023-12-01 01:34:39 25 4
gpt4 key购买 nike

这就是我想做的:使用 php 和 javascript 创建一个 cookie onclick。我正在使用的代码(如下)不起作用,因为我真的不知道我在做什么。我需要它在我的域中使用,并在五分钟后过期。有人可以帮我纠正这个片段吗?谢谢。

<?php
// name of the cookie
$cookie_name = 'testcookie';

// expires in five minutes, also the value of the cookie
$cookie_expire_time = time() + 300;

// check if cookie is set
if(!isset($_COOKIE[$cookie_name])) {
// if NOT set
echo 'Cookie is NOT set. <a href="https://MyTestPage.com/" onClick="window.open(\'https://google.com/\'); setCookie(\''.$cookie_name.'\', \''.$cookie_expire_time.'\', '.$cookie_expire-time.');">Click here to set the cookie, reload the page, and open google in a new tab.</a>';
} else {
// if IS set
echo 'Cookie IS set now.';
}
echo '<script>
function setCookie(cname, cvalue, exdays) {
var expires = "expires="'.$cookie_expire_time.';
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>';
?>

我原来的测试片段有效(如下),只是无法让第一个示例按照这个示例工作。这个有效期是 30 天。如何使用 PHP 在几分钟内传递过期时间?

<?php
$cookie_name = 'testcookie2';
if(!isset($_COOKIE[$cookie_name])) {
echo 'Cookie is NOT set. <a href="https://MyTestPage.com/" onClick="window.open(\'https://google.com/\'); setCookie(\'testcookie2\', \'yes\', 30);">Click here to set the cookie, reload the page, and open google in a new tab.</a>';
} else {
echo 'Cookie IS set now.';
}
echo '<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>';
?>

最佳答案

要在 PHP 中执行此操作,您需要调用 setCookie

<?php
$CookieName = "userName";
$userName = "Test";
$expireAt = time() + 300;
//setcookie(name, value, expire, path, domain, secure, httponly);

setcookie($CookieName, $userName, $expireAt, "/");

更多信息请点击 http://php.net/manual/en/function.setcookie.php

或者你可以使用你本质上拥有的js,但它被包装在一个没有被调用的函数中,至少我不能告诉。因此,如果您执行了类似下面的操作,它只会在页面加载时设置它。

<script>
var minutes = 5;
var dt = new Date();

var expireAt = new Date(dt.getTime() + minutes*60000);

document.cookie = "username=John Doe; expires=${expireAt}; path=/";
</script>

编辑

我相信你想在 PHP 中设置变量,然后将其放入 js 脚本中。这是可以做到的,而且您已经很接近了。

如果这就是您要输出的页面,那么您可以进出php

<?php
//You are doing PHP here
$CookieName = "userName";
$userName = "Test";
$expireAt = time() + 300;
//This is stopping the php interpreter
?>
<!-- Here is html-->
<script>
//This is js on that html the <?= > opens php and you can access variables
document.cookie = `<?=$CookieName?>=<?=$userName?>; expires=<?=$expireAt?>; path=/`;
</script>

关于javascript - 使用此 javascript 和 php cookie 代码时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52937532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com