Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Session variable using javascript in PHP

Is it possible to set PHP session variables using Javascript?

like image 927
Sanjay Khatri Avatar asked Aug 28 '10 09:08

Sanjay Khatri


People also ask

Can we set PHP session value in JavaScript?

The session is stored server-side so you cannot add values to it from JavaScript.

How can set session variable in PHP?

To start PHP sessions, you must use the function session_start() . To set session variables, you will need to apply a global PHP $_SESSION variable . Note: The PHP session_start() function has to be the first thing in your document: all HTML tags come after.

Is it possible to set session variables from JavaScript?

It is impossible to assign session values directly using JavaScript, but we (as web developers) want to use session storage locally to save, retrieve, update data. We can use localStorage and sessionStorage .

Why session_start () is used in PHP?

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.


3 Answers

In JavaScript:

jQuery('#div_session_write').load('session_write.php?session_name=new_value');

In session_write.php file:

<?
session_start();

if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>

In HTML:

<div id='div_session_write'> </div>
like image 140
BGabesz Avatar answered Oct 08 '22 20:10

BGabesz


The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:

$.post('/setsessionvariable.php', { name: 'value' });

You should, of course, be cautious about exposing such script.

like image 22
Darin Dimitrov Avatar answered Oct 08 '22 22:10

Darin Dimitrov


If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.

like image 9
Lèse majesté Avatar answered Oct 08 '22 22:10

Lèse majesté