Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ethar's avatar
Level 5

message: "Cannot modify header information - headers already sent

i use this function to store data in cookies, before upload Project to Cpanel everything working fine (windows machine), after upload, I got this error when click on the add button

data sent to function by ajax

    public function addToCart($pid, $qty)
    {
        if (isset($_COOKIE["shopping_cart_panorama"])) {
            $cookie_data = stripslashes($_COOKIE["shopping_cart_panorama"]);
            $cart_data = json_decode($cookie_data, true);
        } else {
            $cart_data = array();
        }
        $item_id_list = array_column($cart_data, 'item_id');
        if (in_array($pid, $item_id_list)) {
            foreach ($cart_data as $keys => $values) {
                if ($cart_data[$keys]["item_id"] == $pid) {
                    $cart_data[$keys]["item_qty"] = $cart_data[$keys]["item_qty"] + $qty;
                }
            }
        } else {
            $item_array = array(
                'item_id' => $pid,
                'item_qty' => $qty,
            );
            $cart_data[] = $item_array;
            echo 1;
        }
        $item_data = json_encode($cart_data);
        setcookie('shopping_cart_panorama', $item_data, time() + (3600 * 24 * 30), "/");
    }

i got this error

message: "Cannot modify header information - headers already sent

I used

        @setcookie('shopping_cart_panorama', $item_data, time() + (3600 * 24 * 30), "/");

the error disappears but item did not add to cart

0 likes
7 replies
rodrigo.pedra's avatar

The error disappears because the @ is the error suppression operator, so it will hide any errors that happened on that function call, but it won't prevent any error from happening.

Regarding the error cause, try removing (or commenting out) the echo 1; 2 lines above the setcookie call.

As stated in PHP docs:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. 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.

reference: https://www.php.net/manual/en/function.setcookie.php

So as the echo 1; sends an output before setting the cookies, that might be the reason the setcookie call fails.

1 like
ethar's avatar
Level 5

@rodrigo.pedra thanks for you, really helpful. I remove echo 1; and everything work fine.

I used echo 1 to determine if shopping_cart_panorama item_qty updated or add a new product,

question:: now how can determine if new item add, or updated quantity of exist item. plz, help. cause I must return 1 if new item added

rodrigo.pedra's avatar
Level 56

You can try returning after the cookies were sent:

    public function addToCart($pid, $qty)
    {
        if (isset($_COOKIE["shopping_cart_panorama"])) {
            $cookie_data = stripslashes($_COOKIE["shopping_cart_panorama"]);
            $cart_data = json_decode($cookie_data, true);
        } else {
            $cart_data = array();
        }

        $item_id_list = array_column($cart_data, 'item_id');
        $wasAdded = false;

        if (in_array($pid, $item_id_list)) {
            foreach ($cart_data as $keys => $values) {
                if ($cart_data[$keys]["item_id"] == $pid) {
                    $cart_data[$keys]["item_qty"] = $cart_data[$keys]["item_qty"] + $qty;
                }
            }
        } else {
            $item_array = array(
                'item_id' => $pid,
                'item_qty' => $qty,
            );
            $cart_data[] = $item_array;

            $wasAdded = true; // replacing "echo 1;"
        }

        $item_data = json_encode($cart_data);
        setcookie('shopping_cart_panorama', $item_data, time() + (3600 * 24 * 30), "/");
        
        if ($wasAdded) {
            echo 1;
        }
    }

Is this function a controller's method? I would try using Laravel's built in methods for cookie and response manipulation:

public function addToCart($pid, $qty)
{
    // request() is a Laravel helper that wraps around super globals
    // and let you perform several request related tasks
    if (request()->hasCookie('shopping_cart_panorama')) {
        $cookie_data = stripslashes(request()->cookie('shopping_cart_panorama'));
        $cart_data = json_decode($cookie_data, true);
    } else {
        $cart_data = [];
    }

    $item_id_list = array_column($cart_data, 'item_id');
    $wasAdded = false;

    if (in_array($pid, $item_id_list)) {
        foreach ($cart_data as $keys => $values) {
            if ($cart_data[$keys]['item_id'] == $pid) {
                $cart_data[$keys]['item_qty'] = $cart_data[$keys]['item_qty'] + $qty;
            }
        }
    } else {
        $item_array = [
            'item_id' => $pid,
            'item_qty' => $qty,
        ];
        $cart_data[] = $item_array;

        $wasAdded = true;
    }

    $item_data = json_encode($cart_data);

    // cookie() is a Laravel helper to create a cookie object
    // note that we don't need to add to time() here, just tell 
    // the number of seconds when this cookie will expire in the future
    $cookie = cookie('shopping_cart_panorama', $item_data, 3600 * 24 * 30, '/');

    // response() is a Laravel helper that will create
    // a Laravel response object
    // intval will convert true -> 1 and false -> 0
    return response(intval($wasAdded))->withCookie($cookie);
}

If you try this code out, cookies will be encrypted by default. As you seem to be using this cookie client-side you will need to tell Laravel to not encrypt this cookie.

Go to your project's ./app/Http/Middleware/EncryptCookies.php file and add that cookie name to the $except array:

<?php

namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        'shopping_cart_panorama',
    ];
}

Please or to participate in this conversation.