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 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理