重定向与头和javascript代码


Redirect with header and javascript code

我在PHP中创建了一个重定向页面,每当有人访问该页面时,它将在浏览器中添加一个cookie并将用户重定向到其他页面:例如:google.com

要做到这一点,我已经使用javascript重定向,但问题是,当我提取我的url它不显示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>
';

试试吧。我还没有测试过,但它会给你一个正确的想法:

<?php ?>
       <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>
<?php
header("location: https://www.google.com");
?>

我在开始时打开和关闭php标记,因为我假设这将在php文件中。你也可以把你的cookie代码放在一个单独的。html或。php文件中,并在标题前使用include。

include_once 'cookiecode.php';

标题的技巧是在呈现任何html显示到屏幕之前完成任务。我很确定头也必须在打开标签之前完成。

希望这对你有帮助!