Reading cookies with PHP - 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.

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 :)

Related

retrieving session via cross domain ajax

Background:
I'm developing a website tracker using javascript. Here's how it works:
1) A user visits any domain the tracker script is on "anydomain.com". The script makes a successful ajax call in the background to my master domain "masterdomain.com".
2) When "masterdomain.com" receives a request, the following PSEUDO code is run. It works by checking for an existing session and if one doesnt exist it creates a new one.
The first call appears to be fine because I am able to receive a session ID in a response. However, each successive call to "masterdomain.com" creates a new session. AKA the server doesn't find the "should be" existing session.
Sample PSEUDO Code:
if(session exists)
{
// update timestamp for session
}
else
{
// set a new session for visitor
}
// load template
api(array("accepted"=>session_id),callback);
Some Quick Facts:
1) This does not appear to be a same origin issue (as I am able to communicate with the server fine).
2) I have tried this with cookies/sessions both appear to not be working.
3) I am using codeigniter (sessions are set not to expire on page close). I have also tried using/not using database sessions).
This problem can also be solved if there is another way to uniquely identify a user each time a page loads on a server (not using IP).
Any help would be greatly appreciated as I'm about ready to tear the rest of my hair out of my head!!!! :(
This answer is incomplete in that you'll have to do some additional research, but the easiest way (which is not actually particularly 'easy') to do this is to use Javascript to place a hidden iframe to masterdomain.com, and set up iframe communication (e.g. using postMessage) to retrieve the session from that iframe to your page.
With AJAX calls you can only send/set session cookies if the URL you're calling is on the same domain as your calling script. I think you should create an iframe, call ajax from within and it should work fine. By the way, I have no idea what you are trying to track.

protecting/authenticating JSON requests to server

i am using Ajax to send JSON data over to my server for a php script to parse.
for example this is the JSON which will be outputted:
http://myserver.com/parse.php?user=123&point=100&callback......
and the "parse.php" script will GET the points in the URL and give it to that user which the user id is stored in the user=123.
However , if a person directly use "http://myserver.com/parse.php?user=123&point=100&callback......" on their browser without letting my javascript to initiate it , they can cheat their points , which they can set to any amount they like in the URL.
So how can i protect/authenticate the JSON request??
If you're passing the user points via an AJAX request or something similar client-side, then you simply cannot protect your application against cheating. Your user is telling the script he/she scored 100 points, how can you be sure that's the fair number? Pass over the initial data you're using to compute your score, like valid answers for the questions or whatever it is you're measuring.
If you have a login mechanism in your application, you could check for the valid credentials on the server-side when executing your script, without actually passing the user identifier via GET/POST.
Lastly, in your method you can check for the AJAX header and the referer ($_SERVER['HTTP_X_REQUESTED_WITH'] and $_SERVER['HTTP_REFERER']) to make sure the request comes from your JS code, but this is really just a minor tweak which is easy to compromize. Also, not every browser passes the referer header (depends on privacy settings), so further problems may arise.
Require Users to be logged in to invoke parse.php. If the request doesn't supply a valid session id, refuse to take action.
Don't put any game data and logic in client side.
Never trust the client. You always must calculate server-side.
More infos (don't rely on link title, there is a lot infos in answers) : https://gamedev.stackexchange.com/questions/3695/how-do-you-prevent-your-javascript-html5-web-game-from-being-copied-or-altered

proper way to craft an ajax call with php and auth

From a security standpoint, can someone give me a step-by-step (but very simple) path to securing an ajax call when logged in to PHP?
Example:
on the php page, there is a session id given to the logged in user.
the session id is placed dynamically into the javascript before pushing the page to the client.
the client clicks a "submit" button which sends the data (including the session id) back to the php processing page.
the php processing page confirms the session id, performs the task, and sends back data
I'm stuck on how (and whether) the session data should be secured before sending it through an ajax request. I'm not building a bank here, but i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere (given that sources can be spoofed).
PHP can get the session data without you having to send a session ID via javascript. Just use the $_SESSION variable. If you want to check if a session exists you can just do
if(isset($_SESSION['some_val'))
//do work son.
You'll need to use JavaScript to asynchronously pass user input back to the server, but not to keep track of a session.
Don't send your session data with javascript.
You don't need to (in most cases).
Just post the data with javascript and let PHP retrieve the session data from... the session.
Depends on how you setup your session data.
One simple example would be you have a session called username.
When PHP gets the request from javascript you can do: $_SESSION['username'] to retrieve the sessiondata.
This is a very simple example just to show how it can be done.
As noted above, you don't need to send any session identifiers out with your javascript, to the server an AJAX request is the same as any other request and it will know your session just fine. So basically, just don't worry about it, it's already taken care of.
It's another part of your question that worries me.
i'm concerned about so many ajax calls going to "open-ended" php pages that can just accept requests from anywhere
It worries me too; you shouldn't have any "open-ended" PHP pages hanging around at all. Every public .php script should have authentication and authorisation done. The easiest and most maintainable way to achieve this, IMHO, is to have a single controller script (e.g. index.php) that does authentication and authorisation then sends the request to an appropriate controller. Aside from this controller, all other scripts should be outside the document root so that they cannot be called directly.
This means that you only ever have to worry about authentication and authorisation in one place; if you need to change it, it only changes in one place. It means you don't need to worry about accidentally leaving some executable stuff in some library PHP file that's not meant to be called directly. It means you don't need to shag around with mod_rewrite rules trying to protect .php files that shouldn't be in the doc root at all.

Jquery $.post and PHP - Prevent the ability to use script outside of main website

I have a PHP script setup using Jquery $.post which would return a response or do an action within the targeted .php file within $.post.
Eg. My page has a form where you type in your Name. Once you hit the submit form button, $.post is called and sends the entered Name field value into "mywebsite.xyz/folder/ajaxscript.php"
If a user was to visit "mywebsite.xyz/folder/ajaxscript.php" directly and somehow POST the data to the script, the script would return a response / do an action, based on the submitted POST data.
The problem is, I don't want others to be able to periodically "call" an action or request a response from my website without using the website directly. Theoretically, right now you could determine what Name values my website allows without even visiting it, or you could call an action without going through the website, by simply visiting "mywebsite.xyz/folder/ajaxscript.php"
So, what measures can I take to prevent this from happening? So far my idea is to ensure that it is a $_POST and not a $_GET - so they cannot manually enter it into the browser, but they could still post data to the script...
Another measure is to apply a session key that expires, and is only valid for X amount of visits until they revisit the website. ~ Or, just have a daily "code" that changes and they'd need to grab this code from the website each day to keep their direct access to the script working (eg. I pass the daily "code" into each post request. I then check that code matches in the ajax php script.)
However, even with these meaures, they will STILL have access to the scripts so long as they know how to POST the data, and also get the new code each day. Also, having a daily code requirement will cause issues when visiting the site at midnight (12:00am) as the code will change and the script will break for someone who is on the website trying to call the script, with the invalid code being passed still.
I have attempted using .htaccess however using:
order allow,deny
deny from all
Prevents legitimate access, and I'd have to add an exception so the website's IP is allowed to access it.. which is a hassle to update I think. Although, if it's the only legitimate solution I guess I'll have to.
If I need to be more clear please let me know.
The problem you describe is similar to Cross-Site Request Forgery (CSRF or XSRF). To protect you against this you could put a cookie into the browser and have the cookie value sent in the post form too (by hidden field or just add it to $.post). On server side check both those fields, if they match the request probably came from your site.
However the problem you describe will be quite hard to protect against. Since you could easily make a script (or use Crul) to forge all kinds of requests and send to your server. I don't know how to "only allow a browser and nothing else".
Use the Session variable as you say plus...
As MyGGAN said use a value set in a cookie (CVAL1) before rendering the submit forms. If this cookie is available (JS Code Check will verify) then submit.
On the server side:
If this cookie value exists and the session variable exist then the HTTP Request came from your website.
Note: If the script (form) is to presented under another domain DO NOT allow the cookie value (CVAL1) to be set.
Do not allow HTTP Requests on the Server Side Scripts if extra Http Headers Are not available (like x-requested-with: jquery). JQuery sends a request with an X-* header to the server.
Read more on Croos-Site Request Forgery as MyGGAN suggests.
I am not really sure REMOTE_ADDR would work. Isnt that supposed to be the end users IP addr?
Firstly, you could make use of
$_SERVER['HTTP_REFERER'], though not always trust-able.
The only bet that a valid post came from your page would be use a captcha.
try to use HTTP_SEC
// SECURITER
if ($_SERVER[HTTP_SEC_FETCH_SITE] != "same-origin")
die();
if ($_SERVER[HTTP_SEC_FETCH_MODE] != "cors")
die();
if ($_SERVER[HTTP_SEC_FETCH_DEST] != "empty")
die();

How can I get Flash to share the browser cookies/session?

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

Categories