我用 PHP 创建了一个重定向页面,每当有人访问该页面时,它都会在浏览器中添加一个 cookie 并将用户重定向到其他页面:例如:google.com
。
为此,我使用了 javascript 进行重定向,但问题是当我提取网址时,它不显示 google.com
。在提取过程中,它显示同一页面的信息,然后我使用 php header()
进行重定向,它会显示 google.com
信息。
现在我需要帮助才能使此代码与 cookie 和 header 一起使用。
代码:
<?php
header("location: https://www.google.com");
echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Redirecting...</title>
<script type="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
createCookie("karachi","testing",100);
</script>
</head>
<body>
</body>
</html>';
?>
最佳答案
而不是在 JavaScript 上设置它。为什么不使用 PHP。
$date_of_expiry = time() + (86400 * 30); // 30 days
if(setcookie('karachi', 'testing', $date_of_expiry)) {
sleep(3); // sleep 3 seconds
header('Location: http://www.google.com/');
}
或者替代方案:
$date_of_expiry = time() + (86400 * 30); // 30 days
if(setcookie('karachi', 'testing', $date_of_expiry)) {
echo '<h1>Redirecting.. Please wait.</h1>';
echo '<meta http-equiv="refresh" content="3;url=http://www.google.com">';
}
在 JavaScript 上:
echo '<h1>Redirecting.. Please wait.</h1>';
// echo 'logic javascript';
echo '
<script>
setTimeout(function(){
window.location.href = "http://www.google.com"
}, 3000);
</script>
';
关于javascript - 使用 header 和 javascript 代码重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24857516/