Chris Cummings
Chris Cummings

Reputation: 1548

Hold all PHP/HTML output until cookie is set?

I have a PHP page where the first thing I do is set a cookie. To set the data in this cookie I have to do a couple of DB look ups, an XML look up and some math. In the body of the HTML, near the top, I need to display the value of this cookie.

The cookie is setting but on the first load of the page the value is not displaying. If I refresh the page it is set. I can see the cookie is actually setting via Firebug.

It's almost as if, due to the overhead to get the value for the cookie, the rest of the page is going ahead and loading and is trying to display before the value is in place.

So my question would be, is there a way to "pause" all other processing and output until that cookie is set? I am new to ob_start but I thought wrapping my set cookie function with that would do it, but that didn't solve it.

Any ideas?

Upvotes: 0

Views: 468

Answers (3)

Phliplip
Phliplip

Reputation: 3632

Follow up to my comment on the question.

You should build a logic like this:

if(!isset($_COOKIE['yourcookie'])) {
    // The cookie is not set
    // Set the cookie and place the same data in $myCookie
} else {
    // The cookie is set
    // Take the data from the cookie and place it in $myCookie
}

// No the cookie data is always available in $myCookie
var_dump($myCookie);

Upvotes: 1

Glass Robot
Glass Robot

Reputation: 2448

No PHP wont have access to that cookie until the next request.

If the cookie does not exist can you not use the data you are setting in the cookie directly?

Upvotes: 0

jefflunt
jefflunt

Reputation: 33954

Well, rather than delay the page load, you probably want to look into an ajax call via something like jQuery.

What this will essentially allow you to do is, set the cookie in the ajax call, and when it returns, you can update the DOM with the display of the information. That way:

  1. You won't delay your page load unnecessarily
  2. Only when the cookie is set, will the display show up

Upvotes: 3

Related Questions