1

I want my PHP code to differentiate between cookies created by JavaScript (using document.cookie) and PHP (using setcookie()).

Let us suppose below pseudocode:-

<?php

   $X = $_COOKIE['X'];

   if($X_COOKIE_IS_SET_BY_PHP)
      // ALL IS GOOD
   else if($X_COOKIE_IS_SET_BY_JAVASCRIPT)
      // SET A COOKIE USING PHP

?>
2
  • 6
    There is no difference. Cookies are cookies. Commented Dec 29, 2015 at 22:32
  • 1
    Just store the cookie names + values that are set by PHP in a database (which you should be doing anyway). Any cookie variables that are not in the DB, were not made by PHP. Commented Dec 29, 2015 at 22:36

2 Answers 2

6

There is no difference. Cookies are cookies.

The only way (though highly unreliable), is to remember in the session whether you set the cookie from PHP. If not, then it might have been set from JavaScript. But like I said, this is unreliable. The cookie might have been set from PHP in an earlier session, or someone might have manually messed with the cookies.

I think the best way is to use session variables altogether. The session keeps the leading value on the server. If you need the value in JavaScript too, you can set a cookie, or add the value in a small script, but in PHP you never read back the cookie value at all, just use the session value on the server, and to reset the cookie on each request, so the client knows that value too.

Sign up to request clarification or add additional context in comments.

Comments

1

Cookie isn't something stored in server side. It's a piece of data stored in the user's computer / browser. When you use setcookie() in PHP, The server sends the cookie with header which the browser stores in the user's computer (and the browser sends it back with next requests). The place that cookie is stored is the same place where document.cookie would store. Hence, after it's stored, we cannot differentiate it whether it was stored by PHP or Javascript, because no information regarding that is recorded.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.