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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条