How to get PHP session id with jQuery?

Asked

Viewed 1,033 times

0

You know the little code that PHP generates, which is the PHPSESSID?

I was wondering if there’s any way I could take this value with jQuery and store it in a Javascript variable.

4 answers

3

I usually like to do things elegantly. I don’t really like the idea of mixing Javascript with PHP. I would do a route (or page) to return a JSON containing all the information needed to be captured by Javascript and would capture this via Ajax request.

In the archive sess_id.php, do:

session_start();

header('Content-Type: application/json');

$json = json_encode(['session_id' => session_id()]);

exit($json);

In your Javascript file.

 function processarIDSessao(id) {

     // faz alguma coisa com o id da sessão aqui

     console.log(id);
 }

 $.getJSON('sess_id.php', function (response) {
     processarIDSessao(response.session_id);
 });

The advantages of doing this through layer separation is that you don’t have to depend on having Javascript written directly in your PHP script. You could even use an external Javascript in this case.

1

Use this Javascript function to find the session ID based on regular expression:

function session_id() {
    return /PHPSESSID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
}

Or if you prefer to create and associate directly to a variable

var session_id = /PHPSESSID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;

Or the old-fashioned way with PHP:

session_start(); 
$session = session_id(); 

echo "<script language='javascript'>  
var session_id = '$session';  
</script>";

0

Set it as an input value and then take it with jQuery.

in HTML:

<input type="text" id="valor" value="<?=$valor?>" />

in jQuery:

var valor = $('#valor').val();

0

Make a Document.cookie; and from a split on it, then just take the example position, output from Document.cookie "wp-Settings-1=mfold%3do%26libraryContent%3Dbrowse%26editor%3Dtinymce; wp-Settings-time-1=1512653710; _ga=GA1.2.1763768758.1508751393; _gid=GA1.2.2049773337.1512986621; __zlcmid=j4gpfmcsgyFXDD; PHPSESSID=locvlk4vha1037ivs5dcc1irg5"

as they come as a point and comma I only do a split in the point and comma as the code below, they will be transformed into array, each part of the point and comma

var essid = document.cookie;
essid = essid.split(";");

this will return me an array

0:"wp-settings-1=mfold%3Do%26libraryContent%3Dbrowse%26editor%3Dtinymce"
1:" wp-settings-time-1=1512653710"
2:" _ga=GA1.2.1763768758.1508751393"
3:" _gid=GA1.2.2049773337.1512986621"
4:" __zlcmid=j4gpfmcsgyFXDD"
5:" PHPSESSID=locvlk4vha1037ivs5dcc1irg5"
length:6
__proto__:Array(0)

Now I just use position 5 of the variable

console.log(essid[5]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.