Search code examples
phpcookiesheadersetcookie

PHP: Cannot setCookie due to header


I want to set a cookie for my shoppingcart.

This is the form to send the information.

<form action="winkelwagenValidatie.php" method="POST">
            Aantal: <input class="form-control" type="number" name="aantal" value="1" min="1"><br>
            <input type="hidden" name="id" value="<?php echo($product->getProductId()); ?>">
            <button class="button_red" type="submit">Plaats in winkelwagen</button>
</form>

I send it to this php-file

<?php 
  if(isset($_POST["id"])){
  require_once './DAO/WinkelwagenDAO.php';
  WinkelwagenDAO::vermeerderAantalItems(new WinkelwagenItem($_POST["aantal"], $_POST["id"]));
}

But i get this error:

Warning: Cannot modify header information - headers already sent by (output started at /home/supermarktcoppen/public_html/DAO/Verbinding/DatabaseFactory.php:25) in /home/supermarktcoppen/public_html/DAO/WinkelwagenDAO.php on line 103

So in the DAO on line 103 i have this:

setcookie("winkelwagen", serialize($winkelwagenItemArray));

Everything is working fine but i can't set the cookie.

I looked for solutions but non of it can help my problem.


Solution

  • This helped:

    <?php
    ob_start();
    if(isset($_POST["id"])){
      require_once './DAO/WinkelwagenDAO.php';
      WinkelwagenDAO::vermeerderAantalItems(new WinkelwagenItem($_POST["aantal"], $_POST["id"]));
      header('location: winkelwagen.php');
    }else{
      header('location: bestellen.php');
    }