David Yell
David Yell

Reputation: 11855

Reading cookies with PHP

I am trying to read a cookie which I've set with javascript, jQuery Cookie Plugin specifically, and then after that I'm reading it with PHP to write it into a database.

For some reason the cookie is being created on page load, but doesn't "exist" until the page is refreshed. Which means that I'm pumping blank fields into my database tables.

The only way I can think of doing it is to AJAX out to a script which creates the cookie. Or ajax out to a script which returns the data to me in json.

The use case is that I'm creating a simple analytics class for an internal project, and I'd like to write into the database the users resolution, colour depth and all that jazz, which I'm using screen.width etc to get.

Upvotes: 2

Views: 392

Answers (2)

jensgram
jensgram

Reputation: 31508

Cookie data are sent to the server (and forwarded to the PHP interpreter) when the client performs the request. Therefore, a cookie set by JavaScript on the client after the page has been requested from the server will not be transmitted until the next request to same server.

What you have

What you'll have to do is to perform some kind of request (could be done via AJAX) where a PHP script handles the incoming cookie information and stores it in the DB.

What you need

Upvotes: 5

Saeed Neamati
Saeed Neamati

Reputation: 35852

@jensgram is right. These two scenarios can happen:

  1. User requests your page and (s)he hasn't the cookie. You render the response via PHP, but you can't see the cookie at server. Response gets delivered to the browser and on DOMReady (or events like that) you set the cookie. User sends another request (via interaction with your page). Here you have the cookie at server.
  2. User already has the cookie (coming back to your site) and sends a request. You render the response via PHP, but this time, cookie is available in first shot. The rest is the same.

Two suggestions:

  1. To prevent inserting null (or empty) values into your DB, first check to see if cookie exists or not. If not, simply try to set it.
  2. For implementing Analytics, predefined patterns exist. For example, instead of setting a cookie, you can include your script on every page, and on load of each page, you can get the information you need, and send an asynchronous ajax request to your Analytics Collector PHP file. No need for cookie :)

Upvotes: 0

Related Questions