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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度