0

I'm guessing not, but is there a way to set a cookie in PHP without having to put ob_start() at the start of the output?

My problem is, that I am developing a class, which among others, needs to set a cookie. Now I can't tell the person who uses it "you have to make a new instance of the class before you make any output", cause that would be lame. So can I somehow pull it off?

Eduard Luca
  • 6,514
  • 16
  • 85
  • 137
  • Why is it lame to set a cookie before output? – Josh Feb 03 '12 at 15:51
  • It's not lame to do so if it's your code, it's just lame to force another developer to do so because he wants to use your class. – Eduard Luca Feb 03 '12 at 16:06
  • 2
    If you document that the class is responsible for sending HTTP headers (like Set-Cookie), there's nothing wrong with saying that it needs to be used before any output is sent. That's exactly what the `setcookie` documentation says, for example. – JW. Feb 03 '12 at 16:51

3 Answers3

2

You cannot. Cookies are sent as part of the header, so if you've already sent the body, it's too late. Output buffering is the solution.

Perhaps you could use session variables instead.

Matthew
  • 47,584
  • 11
  • 86
  • 98
2

See Headers already sent by PHP

The unprofessional workarounds listed there apply. Specifically:

<META HTTP-EQUIV="Set-Cookie" 
CONTENT="cookievalue=xy;expires=Friday, 14-Dec-12 12:12:12 GMT; path=/">

Or use and set document.cookie.

Community
  • 1
  • 1
mario
  • 144,265
  • 20
  • 237
  • 291
1

This is my workround and is working fine for me.

// Force set cookie now
$_COOKIE['ref_url'] = $_SERVER['HTTP_REFERER'];

// Set cookie after refresh site
setcookie('ref_url', $_SERVER['HTTP_REFERER'], Affiliate::$cookieTime);

// Diplay $_COOKIE
var_dump($_COOKIE['ref_url']);
Arnestig
  • 2,285
  • 18
  • 30
keraj
  • 31
  • 1
  • 6
  • $_SERVER['HTTP_REFERER'] is sometimes empty, so test it up first before using it. $url_referrer = empty($_SERVER['HTTP_REFERER'])?'':$_SERVER['HTTP_REFERER']; – fedmich Sep 22 '12 at 02:04