簡體   English   中英

檢查Cookie值和Cookie是否存在時,PHP未定義索引

[英]PHP Undefined Index When Checking Cookie Value And Cookie Exists

我知道在嘗試使用Cookie之前會先檢查它是否存在,但是在這種情況下,如果我設置一個Cookie,然后嘗試立即使用它而不進行檢查,則該代碼有效,但是我收到“未定義索引”警告在我的php.log中。

下面的代碼確定設備是計算機還是移動設備並設置cookie。 然后,它會檢查Cookie值,以及是否將移動設備重定向到頁面。 (如果沒有,它將輸出頁面,然后在一個框架中顯示內容)。

<?php
// Determine if computer or mobile device
if (!isset($_COOKIE['devicetype']))
{
require_once 'assets/mobiledetect/Mobile_Detect.php';
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
// Any mobile device (phones or tablets).
if( $detect->isMobile() || $detect->isTablet() ){
    setcookie('devicetype', 'mobile',0,'/');
}
else
{
    setcookie('devicetype', 'computer',0,'/');
}
}

// Show flipper page full screen if mobile device
if ($_COOKIE['devicetype'] == 'mobile'){
header('Location: flipping-promotions/'.$_GET['link']);
}

?>

我唯一能想到的是這是一個定時問題,並且在進行檢查時cookie不存在,但是顯然可以檢索到正確的值,因為它可以在平板電腦和手機上正常工作。

有什么想法嗎? 我知道這不是一個主要問題,但是如果您可以阻止除REAL錯誤以外的任何PHP日志記錄,那就很好了。

啊,尤里卡! 在出現與Cookie相關的類似問題后,答案終於浮現在我身上。

如果設置cookie,則無法在腳本的同一循環中檢查該值,只有將頁面輸出發送到瀏覽器后才能識別它。

因此,在這種情況下,假設我剛剛創建了cookie,則需要重新編碼腳本的最后一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM