So I have a page where I'm requesting users to enter a key via an <input>
tag. I would like to store this information in $_SESSION['sessionKey']
when the user clicks a button. Since I'm trying to keep the key moderately secure, I want to avoid passing this information via GET or POST.
Most of what I've found online shows this done by using GET/POST and I'm having difficulty finding information on a method that would not use this approach. I did find this question, which suggests to put JavaScript in a file that has an extension of .php, and from there, use the PHP tags to obtain the $_SESSION variables. I followed this approach like so...
javascript.php
<?php
require ("common/startandvalidate.php");
?>
$(document).ready(function() {
$("#submitButton").click(function(){
<?php $_SESSION['sessionKey']?> = $("#sessionKeyInput").value;
});
});
mainPage.php
<head>
<script src="javascript.php"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<input id="sessionKeyInput" placeholder="Session Key" />
<input id="submitButton" value="Submit" type="button" />
When I look at the page through Inspector (in Chrome) I see the error message:
Undefined index: sessionKey
the require("common/startandvalidate.php");
contains session_start()
, so the session is being initiated...
I think it's not working because $_SESSION['sessionKey']
has never been declared before, so even though I want to assign a value to it, it's trying to see the variable contents, which is undefined. How could I go about assigning this value to the $_SESSION variable?
Sorry if this is a simple question, any resources are appreciated!
$_SESSION
is a PHP array, you cannot set it on the client side via Javascript. The value has to be sent to the server to be stored in the array.
The question you pointed to shows how you can retrieve the data from $_SESSION
, but it won't work for storing data.
The error you see in the console "Undefined index: sessionKey" simply means that the Javascript array named $_SESSION
has no key named "sessionKey".