問題描述
我發現了一段代碼,如果它是第一次訪問,它會重定向,但是當我嘗試使用它時,它只是停留在那個代碼上.我對cookies及其工作原理不太了解,所以也許你可以幫忙!這是 PHP 代碼:
I found a snippet of code that redirects if it's the first visit, but when I tried to use it, it just stayed at that code. I don't really understand too much about the cookies and how it works, so maybe you can help! Here's the PHP code:
<?php
session_start();
if (isset($_SESSION['FirstVisit'])) {
$_SESSION['FirstVisit'] = 1;
header("Location: http://example.com/index.php");
// Don't forget to add http colon slash slash www dot before!
}
?>
那么我該如何修復它,如果這是您第一次訪問該網站,它會將您帶到某個頁面,如果不是,則是默認頁面?
So how could I fix it so if it's your first visit to the site it brings you to a certain page, and if not, the default?
推薦答案
您可以使用以下代碼:
<?php
if (!isset($_COOKIE['firsttime']))
{
setcookie("firsttime", "no", /* EXPIRE */);
header('Location: first-time.php');
exit();
}
else
{
header('Location: site.php');
exit();
}
?>
它會檢查您是否有名為firsttime"的 cookie如果沒有,它會創建它并重定向到您的 FIRSTTIME 頁面...如果是,它只會將您重定向到該網站...
It will check if you have a cookie named "firsttime" and if not, it will create it and redirect to your FIRSTTIME page... If yes, it will just redirect you to the website...
編輯 2021請不要使用這種舊方法,而是使用框架或更好的代碼.現在 10 歲了.
EDIT 2021 Please don't use this old method and either use a framework or better code. This is 10 years old now.
這篇關于第一次訪問時顯示不同的頁面的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!