You know the code PHP generates, which is PHPSESSID
?
I would like to know if I can get this value with jQuery and store it in a JavaScript variable.
You know the code PHP generates, which is PHPSESSID
?
I would like to know if I can get this value with jQuery and store it in a JavaScript variable.
I usually like to do things in an elegant way. I do not really like the idea of mixing Javascript with PHP. I would make a route (or page) to return a JSON
containing all the information needed to be captured by Javascript and would capture it via Ajax request.
In the sess_id.php
file, 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 do not need to depend on having Javascript written directly into your PHP script. You could even use an external Javascript in this case.
Use this JavaScript function to fetch 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 with a variable
var session_id = /PHPSESSID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
Or the old way with PHP:
session_start();
$session = session_id();
echo "<script language='javascript'>
var session_id = '$session';
</script>";
Put it as the value of an input and then get it with jQuery.
in HTML:
<input type="text" id="valor" value="<?=$valor?>" />
In jQuery:
var valor = $('#valor').val();
Make a document.cookie; and a split in it, then just get the position example, exit from the 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 semicolon I just do a split on the semicolon as the code below, they will be transformed into an array, every part of the semicolon
var essid = document.cookie;
essid = essid.split(";");
This will return an array to me
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 only use position 5 of the variable
console.log(essid[5]);