Retrieve $_POST data to send to javascript without using localize script

I have a situation here where I need to access the $_POST data to send a sensitive string to a javascript without using localize script and also not letting the sensitive string be available in the console or source ( html ) of the page.

I researched that AJAX can prevent the sensitive string coming from the PHP to be displayed on the source of the page (html) since this will pose a security issue on our side, but then when I tried this approach the global $_POST is not available on the ajax function on that is hooked on the wp_ajax_{action}.

Is there any other way to do this? Any help will be appreciated, Thanks!

UPDATE Oh and by the way, saving the data in the db is not an option since this will feature on the site will accumulate large number of requests.

Topic encryption ajax php security Wordpress javascript

Category Web


You can use set_transient to write temporary data to the database and get_transient to read the value back. This keeps the data on the server and available across requests. It's kind like a nonce. Keep in mind writing to your database can jam things up when you get a significant amount of users.


If you want to pass hashed data from PHP to Javascript you could use Hashids -- assuming your data is numeric positive numbers.

PHP

$hashids = new Hashids\Hashids('this is my salt');
$id = $hashids->encode(1, 2, 3);
$numbers = $hashids->decode($id);

JavaScript

var hashids = new Hashids("this is my salt"),
id = hashids.encode(1, 2, 3),
numbers = hashids.decode(id);

If you decode anywhere in the JavaScript then someone could potentially get ahold of the salt so it's best to use it only to transport the data.

If you want some random salt, there is an online generator or use wp_salt(). You can also take a look at the way wp_create_nonce() works by adding the logged in user's ID to the salt.


Alternates - some sites warn against using MD5 while others show hashing with openssl.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.