dongzj2015 2015-03-24 18:40
浏览 44
已采纳

PHP:无法设置cookie

I want to set a cookie but it wont work. Im pretty new in PHP but I searched on the internet how to set a cookie, but it doesn't work.

<div id="content">
<?php
    if(isset($_GET['search-item']) && !isset($_COOKIE["searchRequest"])) {
        setcookie("searchRequest", $_GET['search-item']);
        include 'search_engine.php';
    }
    else {
        $page = $_COOKIE['page'];
        if(isset($page)){
            require_once $page;
        }
        else {
            require_once 'startpage.php';
        }
    }

?>
</div>

I really dont know what Im doing wrong :( Can someone help me and explain why this wont work. Everything else works flawlessly

  • 写回答

1条回答 默认 最新

  • 啊啊啊小孔 2015-03-24 18:55
    关注

    First enable error reporting:

    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    

    then you should see following:

     PHP Warning: Cannot modify header information - headers already sent 
    

    Because you cannot output anything before setcookie, and you do here:

    <div id="content">
    

    Manual says:

    Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

    Just move it after you set a cookie:

    <?php
        if(isset($_GET['search-item']) && !isset($_COOKIE["searchRequest"])) {
            setcookie("searchRequest", $_GET['search-item']);
            echo '<div id="content">';
            include 'search_engine.php';
        }else{
            echo '<div id="content">';
            if(isset($_COOKIE['page'])){
                $page = $_COOKIE['page'];
                require_once $page;
            }else{
                require_once 'startpage.php';
            }
        }
        echo '</div>';
    ?>
    

    And beware : it is not safe to include file that comes from cookie, I hope you just experiment, and it is not a part of serious code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失