Passing section of query result into session variables with Javascript - 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.

Related

Inserting data from JS script into mysql database

I have created a script to count down whatever value I submit into a form and then output "the submitted value + the date of the moment I clicked on the submit button" as a result.
But now I want to store the result into my database every time I use the form by using SQL query and then echo all of these results in another page named "log.php" using SELECT SQL query.
var timelog = [];
function myF() {
countdown(s);
log = document.getElementById("log").innerHTML = s + 'at ' + new Date();
timelog.push(log);
}
function logged() {
document.getElementById("timeloggg").innerHTML = timelog;
}
I have tried to assign the result to a variable, but obviously, I cant use this variable outside of the script.
With some googling, I was told to use Ajax, but sadly I couldn't figure out how to insert the data using ajax, because all of the code examples out there are only about calling data from the database.
So any advice on how to insert the result into my database? I'm still a beginner so please explain in detail if you don't mind.
It is possible, of course, to insert data into your database from client side js, BUT DONT! I can't think of a way to do it that would not expose your database credentials, leaving you open to malicious actors.
What you need to do is set up a php script on your server, then send the data (either by POST or GET) you want inserted to that with an xhr request, and let that php script do the insert. HOWEVER, there is quite a bit to securing even that. Google "how to sanitize mysql inputs in php" and read several articles on it.
Depending on what you need to do, you can sanitize the inputs yourself, but the recommended way to do it is with prepared statements, which you will need to read the documentation for your specific implementation, whether it's mysqli or pdo in mySQL or some other library (say if you're using SQL, postGRE, Oracle, etc).
HTH
=================================================
Here is how to do it in js, BUT DONT DO THIS, unless you are never going to expose this code outside of your local computer.
var connection = new ActiveXObject("ADODB.Connection");
var connectionstring = "Provider=host;Data Source=table;User Id=user;Password=pass;";
connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");
var sql = {{your sql statement}};
rs.Open(sql, connection);
connection.close;
==============================================
For php, do something like this, replacing host, user, pass, db with your actual credentials and hostname and database:
$db = new mysqli({host}, {user}, {pass}, {database});
if($db->connect_errno > 0){ die ("Unable to connect to database [{$db->connect_error}]"); }
to set the connection. If this is a publicly accessible php server, then there are rules about how to set up the connection so that you don't accidentally expose your credentials, but I'm going to skip that for now. You would basically save this into a file that's not accessible from the outside (above the document root, for instance) and then include it, but database security is a complex topic.
To get the values you passed in the query string of your ajax call:
$val1 = $_GET['val1'];
$val2 = $_GET['val2'];
Then to do the insert with a parameterized query:
$query = $db->prepare("
INSERT INTO your_table (field1, field2)
VALUES (?, ?)
");
$query->bind_param('ss', $val1, $val2);
$query->execute();
Now, here you're going to have to look at the documentation. 'ss' means that it's going to treat both of those values you're inserting as strings. I don't know the table set up, so you'll have to look up the right code for whatever you are actually inserting, like if they were integers, then 'ii', or 'si' would mean the first value was a string and the second one was an int.
Here are the allowed values:
i - integer
d - double
s - string
b - BLOB
but look at the documentation for prepared statements anyway. I used msqli in this example.
You might want to check Ajax requests.
I would suggest to start here.
What you will do is basically create asynchronous requests from javascript to a php file on your server.
Ajax allows web pages to be updated asynchronously by exchanging small
amounts of data with the server behind the scenes. This means that it
is possible to update parts of a web page, without reloading the whole
page.

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.

How to pass encrypted data via browser (HTML5) session variable

I am trying to pass encrypted data via a browser/client session variable - not to be confused with server-side session variable:
encrypt:
var encrypted_user_id = CryptoJS.AES.encrypt(user_id, cipher_pass);
var encrypted_user_password = CryptoJS.AES.encrypt(password, cipher_pass);
sessionStorage.setItem('user_id', encrypted_user_id);
sessionStorage.setItem('user_password', encrypted_user_password);
decrypt:
var encrypted_user_id = sessionStorage.getItem('user_id');
var encrypted_user_password = sessionStorage.getItem('user_password');
var plaintext_user_id = CryptoJS.AES.decrypt(encrypted_user_id, cipher_pass).toString(CryptoJS.enc.Utf8);
var plaintext_user_password = CryptoJS.AES.decrypt(encrypted_user_password, cipher_pass).toString(CryptoJS.enc.Utf8);
There is no error, but the plaintext is empty string.
If I perform the exact same encryption/decryption using variables instead of sessionStorage it works fine.
What am I not understanding? Is there something about session variables that is different than a local variable?
So I've made a fiddle to test it out. And I think the problem (although in fairness your original code seemed to work for me too) is that for the encryption you should do this instead:
var encrypted_user_id = CryptoJS.AES.encrypt(user_id, cipher_pass).toString();
Why? Without the to string, you're storing an object that JSON can't serialize, so when you're getting your object back from session storage you're getting back something different than you intended.

Store variable using sessions

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();

How to read the value of variable in JS in the scope of JSP on the same page?

I have a JSP page in which third party sign-in plugin is used, which is JS. After sign-in is successful, the user-id obtained in JS has to be used in JSP to maintain session by storing that value.
For this, I tried 'manipulating' jQuery but that works only if the JS value is a literal or is pre-known. But here in this case, value is fetched at runtime as per sign in.
Also tried <% String s = "<script>document.writeln(var)</script>"; %>
But again the above problem. works only when value is known before hand.
document.getElementById("ppurl").innerHTML = ppurl; prints the value. But I want to store it.
So, how to achieve the purpose of passing a variable's value in JS to JSP?
Assuming your third party sign-in plugin is client-side JavaScript:
Remember that the JavaScript runs when the page reaches the client. The JSP code has long since completed and so is no longer in the picture.
You have three options that I can immediately see:
Send the data to the server using Ajax or similar.
Refresh the page (sending the login data to the server as part of the refresh).
Update whatever it is on the page that you want to have this value in it via the DOM.
#1 and #2 should be fairly self-explanatory.
For #3: Say you have various forms on the page and you want to make sure that the login token or whatever it is you get from the client-side plugin gets sent with the form using a hidden field in the form with the name tokenField. You could do this:
function putTokenOnForms(token) {
var forms, index, form;
forms = document.getElementsByTagName("form");
for (index = 0; index < forms.length; ++index) {
form = forms[index];
if (form.tokenField) {
form.tokenField.value = token;
}
}
}
You can do much the same with links in a elements (adding to the href property of each link that goes back to your server), etc.
The page outputting the JavaScript to the client cannot read data back from that JavaScript.
You need to initiate a new HTTP request (e.g. using XMLHttpRequest or setting location.href) that passes the data back to the server and then read it in (e.g. from the query string or POST data).
Store it in a cookie using JS. Read it back in JSP.
In your JS, after you get the userID, you can do:
document.cookie = 'myuserid='+userID;
In your JSP, you can read it back like:
Cookie[] cookies = request.getCookies();
String userID;
for(int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
if (c.getName().equals("myuserid")) {
userID = c.getValue(); // c.getValue() will return the userID
break;
}
}

Categories