1

I need to use cookie in php that has to created in jsp.

I have tried like below. Jsp code for create a cookie:

Cookie userNamecookie = new Cookie ("username", snUser.getUsername());

PHP code for read cookie:

<?php
if (isset($_COOKIE["username"]))
  echo "Welcome " . $_COOKIE["username"] . "!<br>";
else
  echo "Welcome guest!<br>";
?>

But i am not able to read the cookie in php. Can any one please help me.

Venu Annaram
  • 287
  • 2
  • 8
  • 16

1 Answers1

3

Cookie access is restricted to domain and path. The browser won't send the cookie back to the server if it's in a different domain or path. If you don't explicitly set the path via Cookie#setPath() before adding it to the response, then it defaults to the current URI. In other words, only the JSP itself and all other JSPs in the same folder or subfolders have access to the cookie.

If the PHP code runs in same domain, but a different path, then you need to explicitly set the cookie path to /.

Cookie usernameCookie = new Cookie("username", user.getName());
usernameCookie.setPath("/");
response.addCookie(usernameCookie);

If the PHP code happens to run in a different subdomain, e.g. php.example.com instead of jsp.example.com, then you'd need to explicitly set the cookie domain to a common one as well.

Cookie usernameCookie = new Cookie("username", user.getName());
usernameCookie.setDomain(".example.com");
usernameCookie.setPath("/");
response.addCookie(usernameCookie);

(yes, the leading period is significant)

If the PHP code happens to run in a different domain, then it's end of story as to cookie sharing. You'd better store the data you'd like to share in a common DB and pass its unique key around as request parameter, if necessary in flavor of UUID.


That said, it's pretty scary to observe that you explicitly said "jsp code" instead of "servlet code" or even "java code". I think it's time to read How to avoid Java code in JSP files? and our servlets wiki page. Further, it's also scary to observe that you're carrying the username around in a cookie. Do you know that cookies are manipulatable by the client? I.e. the enduser can easily edit the cookie value from e.g. "John Doe" to "Joe Bar". It's not exactly clear what your concrete functional requirement is, but you should at least absolutely not use this approach in case you want kind of "single sign on" across PHP and JSP pages on same (sub)domain. Rather store kind of an UUID as cookie value, which is linked to a shared database.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555