How can PHP see client side cookies?
To elaborate:
When working with PHP & Javascript, I understand that PHP gets processed on the server side. While Javascript happens on the client side.
In Javascript I can check and set these client cookies. That makes sense.
However, with PHP, if I check a client cookie value as part of a conditional statement that also sets , how is PHP able to see the clients cookie value while the PHP is happening on the server side?
Here's an example of the PHP conditional that lives in a php file:
<?PHP
if ($_COOKIE["name"] == “Mickey”) {
setcookie(“fulsome”, “Mickey Mouse”, time()+3600);
}
?>
There is no such thing as a client side cookie.
A cookie is a piece of data associated with a set of URLs in a browser. Every time the browser makes an HTTP request to one of those URLs, the cookie is included in the Request headers.
They were originally designed to be set via HTTP Response headers.
An API was added to browsers that allows them to be created and set by JavaScript. These are still regular cookies though and will be included in every request to the associated URLs.
It is possible to mark a cookie as http_only which will cause browsers to prevent access to that cookie from JavaScript. There is no direct equivalent for imposing a similar limit going the other way. The closest you could come to that would be to use something like Local Storage instead of cookies.
how is PHP able to see the clients cookie value while the PHP is
happening on the server side?
The reason is that each request to server also bring cookies in headers like i have inspected in chorome network tab, my php website and got this:
Cookies are store on client side but are accessible on server side through request header. As #Quentin stated in his answer "Every time the browser makes an HTTP request to one of those URLs, the cookie is included in the Request headers."
(Based on the comments, I wanted to leave a full answer as I understand it).
HTTP headers include existing cookies for the domain/site.
When PHP checks a cookie, the cookie & it's value got there via the HTTP Header that was sent in the call to the php file.
When PHP sets a cookie, it will be sent with the HTTP Header going back to the client, where it will then be set up on the client.
For a full list of what is sent in the Header, and the response back Header, see this:
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
You'll see Cookie in the Header Field List, and Set-Cookie in the list of response fields.
Related
Does anyone know if Unity supports PHP sessions?
For example, let's say that a user signs into their account in Unity and submits the login information through WWW stream. Once logged in, I assign a session variable in my php script: $_SESSION['name]=name.
My question is, when the user comes to submit another request through Unity will the client still be able to access the session variable?
Session data are data from a database connected to an id, which is used in the communication between client and server. Usually a cookie.
I can't say for certain, but I very much believe that the WWW class will ignore/forget cookies.
Unity sends a request (with only the data you define) to PHP
PHP sets a cookie corresponding to that session & responds to the request
Unity gets the response with headers (and cookies in the headers)
Repeat
PLEASE NOTE: I have not tested this, it is theoretical, but educated, guesses.
Suggested solution
You can set headers in your request that you build in Unity. If you save the headers from the response and add those to the request each time, you should be able to emulate the behaviour you're seeking. So basically:
Unity sends a request (with headers = previousResponseHeaders) to PHP
PHP reads the headers and connect your cookie to previous session & responds to the request
Unity gets the response with headers (and cookies in the headers)
Repeat
You set headers by doing something like this:
var headers = new Dictionary<string,string>();
headers.Add("Cookie", "key=value; semicolon=separated");
WWW www = new WWW("https://example.com", null, headers);
Much like the question asked in Detect if cookies are enabled in PHP and Check if cookies are enabled I'd like to know if cookies are enabled.
I am, however, trying to make this as transparent as possible for the user and as such I'm not interested in having some "cookietest=1" parameter appended to my URL.
I know I can just redirect back to the page the user originally entered, unset "cookietest=1" GET parameter and just tell the original page if cookies are disabled or not through sessions, but...
I'm currently using CodeIgniter and don't want to mess up CodeIgniter sessions, hence not using PHP sessions to store the cookie enabled/disabled state.
I'm actually not sure if using PHP sessions will mess up CodeIgniter sessions, but even if it doesn't I'm still interested in knowing if there is some ingenious solution out there, that can do the cookie check without setting a GET parameter or using sessions (redirect are fine, however)?
Update
Seems I need to clarify a little bit:
I want to know if cookies are enabled client side. I've already tried the method described in the questions I linked to, i.e.:
Set cookie.
Redirect to either a check cookie PHP page or the same page with a "cookietest=1" GET parameter.
See if the cookie is still set: If yes => Hooray, cookies are working!, otherwise => Boo, cookies are disabled.
The thing I'm asking is whether or not it's possible to do this without setting the GET parameter (because this becomes visible in the URL). The answer to that question is "Yes, if you use PHP sessions".
My next question is then: Is it possible to do without setting the GET parameter AND without using PHP sessions?
Basics: You can't know if a user has or not enabled cookies until you send one cookie to the client and you recive the same from him.
So the flow:
Client Request
Server Response (+ cookie)
Client Request (+ cookie)
can't be avoided from any way
You can track if cookies are enable using some test request (ajax, image, etc)
For example you can use a simple 1px image or any logo image served from your php script and you can track if cookies are enabled or not.
So the flow is now:
Client Request
Server Response HTML (+ cookie)
Client Request remote page resources (js, img, css) (+ cookie)
Server Response with page resource requested
Something like
<?php
// domain.com/some.js
if (isset($_COOKIE['test']))
$_SESSION['cookies_enabled'] = true;
echo <<JS
<someJS code or nothing>
JS;
?>
I looked into this a LOT a while ago and it seemed every way had its flaws. One thing I took into account as well was how the cookie check would work if the user were to update the page or go back to the page via the back button.
Apparently, for the server to see whether the client accepts cookies or not the client has to send an additional HTTP request after the server has attempted to set a cookie, in which the server looks for a cookie header indicating that the client accepts cookies (no header = cookies not accepted). This additional request can be a redirect to another page (see the usual method with a $_GET parameter acting as a flag saying if an attempt to set the cookie has taken place or not) but the important thing is really that it's just another HTTP request. What I ended up doing was wrapping my entire page in a HTML FRAMESET:
<?php
setcookie('test', 1, time() + 3600);
echo '<HTML>
<HEAD>
<TITLE>
</TITLE>
</HEAD>
<frameset rows="100%" cols="100%">
<frame src="next.php">
</frameset>
</HTML>';
?>
...then in the additional HTTP request for next.php I know that there will be a cookie header included in the request if the client has accepted cookies and therefore I don't have to use a $_GET parameter as a flag indicating this. Next.php thus looks like:
<?php
if(count($_COOKIE) > 0){
//Set some variable that indicates to the rest of the script that cookies
//are enabled.
}
else {
//Set some variable indicating that cookies are disabled
}
//Output the rest of the script and HTML code to be displayed
?>
I thought about doing the same thing but sending the additional HTTP request from an IMG tag instead of a FRAMESET but I ran into trouble as to how I would indicate to the parent script via an image whether cookies were set or not and therefore I ended up doing it this way. The ONLY flaw I see in this method is that if the user right-clicks inside the frame and choose to update only the frame (not the entire page) then the frame will falsely claim that cookies are disabled but compared to the downsides of all the other ways, I thought that was acceptable.
EDIT: I should also add that I made a point out of doing this without Javascript as well.
I would use php.ini settings to find such things out.
Maybe like this:
if (ini_get("session.use_cookies") == 1) {
print "cookies enabled";
}
While you could just check if php has cookies enabled a very simple test would be to just set a cookie and then try to read it.
If you successful read it, it worked.
This would also inform you if the client disallows cookies.
I'm a newbie and at the moment I'm learning PHP by designing a small and basic web page. I want to add a cookie handling script to my code. First I was planning to do it by Javascript. But when I browsed cookie managing functions of PHP and saw how detailed they are, I got very surprised.
But I don't understand the mechanism behind that. PHP is said to be a server-side script. How can it control cookies in my computer? How does it do that?
Cookies are set by either setting HTTP Headers (server-side) or JavaScript (client side).
What PHP does when you call the setcookie() function is generate a HTTP response header like this:
Set-Cookie: name=value
For detailed information check this Wikipedia article:
http://en.wikipedia.org/wiki/HTTP_cookie
When a user clicks a link, request headers are sent to the relevant server holing the website. The web server then responds using Reply Headers. The reply headers then have a space at the wnd that signal to the browser that the HTML is incoming.
The reply headers contain stuff like cookies, the encoding that incoming data will be in e.t.c. So the web server doesn't control the cookies per se but it instructs the browser on what to do and what to store i.e. cookies
The first time a browser visits a site, the php code can send back a cookie instruction at the front of the page content. When it gets back to the browser the browser sets a cookie record. This record can have a set lifetime. If the cookie is still set the next time the browser visits the server it sends that cookie along with the request. The php code can check it is set and decide what to do. For example, if the cookie is not set the server could send the login page instead of a content page that would be sent back if the cookie is set in the request.
So yes, php does send cookie set orders to the browser.
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.
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'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.
#jensgram is right. These two scenarios can happen:
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.
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:
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.
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 :)
I'm building a PHP-based web app and am integrating a Flash-based charting engine. The Flash chart needs to make a AJAX request for its data. This request fails because it is seen as a new user agent and doesn't contain the PHP session cookie to identify it. So, it gets redirected to the login page.
I've read a few hacks to make this work, including supplying the session ID on the querystring, but that opens up security holes. How can I get Flash and PHP to share cookie-based session state automatically and stay secure?
In IE it will work naively. In firefox, the only way to achieve this is to POST the session id into the flash script (the php processor that is), and have it restore the session from that.
If the session cookie is initiated early enough, then it should be OK. I've had a similar problem with cookies shared between JavaScript AJAX and Flash requests (if you want to call that AJAX too, go ahead :-) ), and we solved them by making sure the JavaSCript finished the request that initiated the cookie early enough so that when the Flash sent the request, the browser already had the session cookie.
Also making sure the cookie path was set to "/" was a good idea.
That being said, if you can't get it to work - as dirkgently said - you can store the information in the HTML DOM using a JavaScript AJAX call, and then fetch it from the Flash object using an ExternalInterface call. But do make sure to set at least "allowScriptAccess=sameDomain" on your Flash object
You should be aware that transmitting a session ID in a Cookie: header, or in the argument field of the GET HTTP directive is of no different security.
Use ExternalInterface to talk to the Flex chart. Some browser related information can be passed around via the LoaderContext and BrowserManager classes as well. Dig in a bit into the AS3 documentation.
you can try and send to php 2 parameters one session_id and a second one that is an key that combines some information from the client ( ex ip ) and encrypt it with a key stored on the server and on the request from flash you check to see the second paramaters matches the client request, this way if somebody trys to do a session stealing they cant because they will not match the second param