Equivalent of PHP Sessions in JavaScript - php

I was going to ask about how to implement sessions in JS,I found few functions that can be used like this example I found :
String exforsys = request.getParameter("test");
session.setAttribute("test", exforsys);
And then just use session.getAttribute( exforsys);
But no response, I guess it's only used in servlets or something.
Anyway, I decided that maybe someone has an alternative way other than just use sessions, what am trying to do is click on a link in one page and depending on which link was pressed I will load different information.
Since its a onclick function, I'm stuck with JS!
So I need to pass this information to the second page, cookies works well cause it can be handled with both PHP and JS easily but some computers deletes cookies and that wouldn't be nice!
Any suggestions or other ways I can reach what I want but with out using sessions?

Sessions are server variables. Thus cannot be used by JavaScript.
However, you can retrieve the session variables, through ajax request.
Script (jQuery)
//This portion will be triggered once the DOM is loaded and is ready
$(document).ready(function() {
$.post("getsession.php",
{ "variable" : "yourneededsessionvariable" },
function(data) {
//data contains your session data
}
);
});
PHP
//getsession.php
<?PHP
session_start();
echo $_SESSION[$_POST['variable']];
?>

Use local storage or client controlled cookies.. Sessions uses server-controlled cookies. Cookies are just small files that resided on the client.

A session handle is stored in a cookie. If cookies are not accepted, the server will add the sessionID to the URL. If you do not have cookies, you cannot persist anything except in the url.
Why does "onclick" stop you from using sessions? You can ajax things to the server and add them to the session onclick

A session generally means "Some data stored on the server and associated with a user via a token stored in a cookie". You can't do that with client side JavaScript (for obvious reasons).
You could store data directly in a cookie.
If you are willing to sacrifice wide browser support, then you can get increased storage by using one of the client side storage mechanisms introduced by HTML 5 and Friends.
maybe someone has an alternative way other than just use sessions,what am trying to do is click on a link in one page,and depending on which link was pressed I will load different information.
Just link to different pages.
some computers deletes cookies and that wouldn't be nice
If they delete all cookies, then a session isn't going to work either.

Append the data you want the next page to get on the query string.
123
456
Then on foo.html you can inspect location.href to see what was passed in. THere is no need for cookies here.

PHP is a server scipring language while javascript is client end language
you cannot literally make sessions in javascript

Why not just use request parameters? i.e. http://yourserver.com/page.php?link=1

Related

How to add values to a php session with jquery

I have an audio player and I want to send the time when I access another link, so when it's loaded it can continue from the exact time I pass in the session
any help?
Why would you need to use PHP sessions for this?
I'd use a cookie, or if older browsers are'nt an issue, local storage, or maybe a script for using cookies on older browsers and local storage on newer browsers.
There's a handy cookie plugin for jQuery.
Local storage is pretty straight forward aswell:
localStorage.setItem('timeIleft', time_variable);
and to retrieve:
var user_left = localStorage.getItem('timeIleft');
You need to call an AJAX requets to do that.
The URL will be a php page and will retrieve your data using $_POST['param-name'].
Or, check this way to call php page http://www.xajaxproject.org/

How to implement persistent page using php/jquery?

You load a page display.php with a lot of ajax content in different areas of page.
A user clicks inside the page and some part of ajax content changes. Now when a user
clicks the reload button on the browser it will loose the content loaded from ajax requests.
How do I retain all information loaded by ajax? Much Thanks.
You have two options:
store information in localStorage (in JavaScript),
store information on the server, eg. using server sessions,
plus one additional possibility (if applicable in your case):
use pushState and onpopstate to support URL changes without requests to the server (alternatively solve it with onhashchange),
You may also use location hash.
Write something on the location hash as an ajax call runs. So when you reload the page, the on $(document).ready you may read that hash and load the data again with ajax calls.
This approach has a point, you can share the url#hash as a link to that data with other persons. It's not dependent to your session or your localStorage.
Krister has it right. Store the changes in a session variable and have a recall function on $(document).ready that checks session variables. ;)

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.

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

How to reset state of DataTable defined with filters or/and search field, with PHP

Working on PHP application, that uses DataTables (https://datatables.net) on several layouts.
Can I somehow reset all DataTable's filters and search data, after end user logged out from application? In other words, to clear all cookies that DataTables library created, if it's possible with PHP functions..
Main idea is to reset application to it's main state after user is logged out from application.
Thank you in advance!
The documentation says: (https://datatables.net/examples/basic_init/state_save.html)
The built in state saving method uses the HTML5 localStorage and
sessionStorage APIs for efficient storage of the data.
It means you cannot reach it with PHP.
However you can change the storage of filter parameters to cookie or server side.
Alternative options of using cookies or saving the state on the server
hrough Ajax can be used through the stateSaveCallback and
stateLoadCallback options.
You should write code which:
- save the filter parameters to cookie what you can remove on logout with PHP
or
- save the filter parameters to database via AJAX and you also can remove it on logout with PHP
example is here:
https://datatables.net/reference/option/stateSaveCallback
In case anyone out there is interested in a solution to this:
As some people rightly pointed out, there's no way to delete localStorage from PHP because PHP works only on the server and localStorage is client-based.
However, a way to achieve what OP wants is make sure that the page shown after logout has the JS needed to delete localStorage. For example, say that after logout, the user gets redirected to comebacksoon.php; what you need is to make sure that in the html of this comebacksoon page, you include:
<script>
localStorage.removeItem(keyYouWantToDelete);
</script>
It should be noted that if the user closes the window before comebacksoon.php is loaded, localStorage won't be deleted, but this approach has worked for me in most cases.

Categories