Store variable using sessions - javascript

I have a variable which is updated on every page shift, but I want to store the value in the first call for good somehow.
The variable is e.g
$sizeOfSearch = $value['HotelList']['#activePropertyCount'];
First time the page loads it's 933, on next page the same value is retrieved but it's now different e.g 845. This goes on page for page.
What I want is to store 933 for good. So I can show this number on every page.
Can I somehow store the first time this value is retrieved ? (I get the value via REST request)
Sessions maybe or ?

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. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.
So, on every page make sure to start it with:
<?php
session_start();
Then, you set the value like this:
if(!isset($_SESSION['name'])) {
$_SESSION['name'] = $sizeOfSearch;
}
Whenever you need the retrieve the value use this:
print $_SESSION['name'];
This session will keep store the variable as long as you don't destroy it. Code for destroying a session:
session_destroy();

Related

Passing section of query result into session variables with Javascript

I'm having trouble passing the result of a query into a session variable, I think that the easiest way to do this is through Javascript. I have the query result showing but they will not pass to the session variable. At the end of each query resultant row, I have an add button that will activate the JS function to add to the session variable.
Query Result:
echo '<tr><td>'.$products['Name'].'</td><td>£'.$products['Price'].'</td><td>'.$products['Category'].'</td><td><img src="'.$products['Image'].'" width=100px /></td><td>'.$products['ProductID'].'</td><td><button onclick="setProduct('.$products['ProductID'].')">Add to Basket</button></td></tr>';
JS Function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
Code displaying contents of session variable:
echo $_SESSION['ProductID'];
$_SESSION is a server-side variable. You'd most likely want to set a $_COOKIE instead. Those are accessible on the client-side.
In addition to the answer posted, you can create a jQuery post request (or you can use AJAX) and send the JS session as value to a PHP file where you can access that value and create the corresponding PHP session.
Let's say, your JS function:
function setProduct(x){
var productID = x;
'<%Session["ProductID"] = "'+$products['productID']+'";%>';
// ...
$.post('example.php', { session_name: YOUR-SESSION-NAME, session_value: YOUR-SESSION-VALUE });
example.php:
if (isset($_POST['session_name']) && isset($_POST['session_value'])) {
$_SESSION[$_POST['session_name']] = $_POST['session_value'];
}
This is not taking into consideration security issues you might face. You should encrypt your data before sending it.

Ajax inside wordpress security

Before I get to the question, let me explain how we have things set up.
We have a proxy.php file, in which class Proxy is defined with functions that call upon a rest for creating/editing/getting Wordpress posts, fields etc.
Then, we have a proxyhandler.php, in which Proxy class is initialized and serves as a handle between proxy.php and a javascript file.
In javascript file we have an ajax call to proxyhandler.php in which we send our secret and other data.
Now, the problem arises here:
We define the secret through wp_localize_script, by using md5 custom string + timestamp. We send the encripted string and timestamp through ajax to proxy handler, where we use the previous (hardcoded inside proxyhandler) string and timestamp to generate a md5 string again, and check the one sent against the one generated. If they are the same, we continue by doing whatever was requested, if they dont fit, we just return that the secret didn't match.
Now, the real issue comes here - by using wp_localize_script, the variable for the secret is global and as such, anyone can utilize it via dev tools and can send any ajax request to proxyhandler that they want.
What would be the proper procedure to make it more secure? We've thought of doing this:
Instead of using wp_localize_script, we put the script inside a php file, we define the secret using a php variable and then simply echo the secret file into ajax. Would this be viable, or are there any other ways?
Instead of sending an encrypted string in global scope, then check against it, you should use nonce in your AJAX request:
var data = {
action: 'your_action',
whatever_data: who_know,
_ajax_nonce: <?= wp_create_nonce('your_ajax_nonce') ?>
};
Then, use check_ajax_refer() to verify that nonce:
function your_callback_function()
{
// Make sure to verify nonce
check_ajax_refer('your_ajax_nonce');
// If logged in user, make sure to check capabilities.
if ( current_user_can($capability) ) {
// Process data.
} else {
// Do something else.
}
...
}
Depend on the AJAX METHOD, you can use $_METHOD['whatever_data'] to retrieve who_know data without needing to use wp_localize_script().
Also remember that we can allow only logged in users process AJAX data:
// For logged in users
add_action('wp_ajax_your_action', 'your_callback_function');
// Remove for none logged in users
// add_action('wp_ajax_nopriv_your_action', 'your_callback_function');
The final thing is to make sure NONCE_KEY and NONCE_SALT in your wp-config.php are secure.

Adding extra variables to a URL

Using JavaScript I managed to add a variable to a page and used $_GET on the new page to use the variable to perform queries. This first implementation worked fine as I was only using one variable. However I need to use two variables now and I'm running into some problems while doing it. If I combine both variables in the first page like shown below, the values are mixed up where my db value goes to my table id.
window.location.assign("test.php?db=&tbl=" + yourDB);
I tried putting both IDs only in my new page and using reload as my DB value would already have been passed. Using
window.location.reload("test.php?db=&tbl=" + yourTbl);
But this doesnt work either.
How can I get the url to have both my DB and table in the correct format? Like
test.php?db=test&tbl=customer
EDIT
yourDB variable is passed from a select form option from a different page which in turn opens the new page where the yourTbl variable exists.I can't therefore call yourDb
window.location = 'test.php?db=' + yourDB + '&tbl=' + yourTbl ;
'OP is asking: yourDB since this variable stores the values of select options from a different page.Any ideas'
My answer is 'Get value from selection menu list in the another page, and save this value into local storage or session storage.'
Something like this,
// save your db
window.sessionStorage.setItem("db", yourDB)
// get your db
var obj = window.sessionStorage.getItem("db");

Codeigniter: calling model from view - DB content seems frozen

I am trying to use javascript in my CI view to update (without refresh) a data model every 2 seconds, for my use case where the database contents can be changed by other users.
<script type="text/javascript">
var refreshFunc = setInterval(function() {
<?php
$this -> load -> model('m_cube', '', TRUE);
$stamp = $this -> $m_cube -> stamp();
?>
var stamp = "<?php echo $stamp; ?>";
console.log(stamp);
}, 2000);
refreshFunc;
</script>
I am using JS setInterval to create the 2 second loop, and calling the CI model to retrieve data from the Postgresql database. In the simplified code sample, it's just asking the DB for a timestamp. The problem is that the timestamp written to console doesn't update - something is stuck.
2013-10-21 14:35:54.168-04
2013-10-21 14:35:54.168-04
2013-10-21 14:35:54.168-04
...
Same behavior when querying a table of real data - it doesn't return up-to-date values.
Why does the model access a "frozen" version of the DB?
It's not stuck or "frozen", it's that you had a bit of confusion on what comes before and what after.
I don't see you using AJAX, so by the time your php has been processed (i.e, the data fetched from the db and assigned to $stamp) the page - html, css and javascript too - are yet to be generated and served by the server, nor outputted by the browser.
This means that inside your setInterval you always have the same value, which has been already generated, and thus you keep reprinting the same string.
If you want a continue update, you need to keep requesting the data to the server, and that's where AJAX (Asynchronous JavaScript and XML) can be handy since it runs as a separate request from the main one, so you can work on two different "levels" and fetch content while the rest of the page remains static (already served and outputted).
If you're using jQUery you can look into $.ajax(), which makes this kind of things pretty easy.
When this script runs at the server it fetches the model data and replace the <?php ?> tags with the results. So when it comes to client browser, it doesn't contact server every 2 seconds, but logs the stamp value every 2 seconds. If you want it to be updated you should consider using Ajax technology.

Check for undefined javascript variable?

I am trying to check if a variable is defined, if it is then an ajax request is run...If it is not I want the user to be redirected to a separate page where the variable is set.
for example I want something like this:
// if variable is undefined
if (typeof accessKey === 'undefined') {
alert('the variable is not set!');
} else {
var accessKey = 'some random string generated from google';
alert('the variable is set!');
proceed to refresh the page and run through check again.
}
So the first time the page is run, it checks if the variable is set. If the variable is not set it will set the variable and then reload the page and run through the check again.
Problem is 'accessKey' always returns undefined but the code runs through as if the variable is defined. Why?
If the variable is not set it will set the variable and then reload the page [emphasis mine] and run through the check again
There is your problem: variables (or any other piece of js code) do not persist between page reloads.
If you need stuff to persist, you have to use one of these:
Server-side sessions or databases (using ajax to pass data to the server and persist it there)
Client-side storage (such as localStorage).
Cookies (can be generated at client-side or server-side)
Save the value in hiddenfields or in cookie.

Categories