Jaketr00 Jaketr00 - 1 year ago 51
PHP Question

Easiest way to create a unique code to use between Javascript and PHP?

I'm looking for a way to create the same code in both JavaScript and PHP as a security measure to make sure you can't just access the PHP script, but only when this JavaScript says to access it.

I am using AJAX to access a PHP logging file

var xhttp = new XMLHttpRequest();
xhttp.open('POST', 'log/', true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

is the unique code.)

In the PHP code I want to add

if ($_POST['uniqueCode'] === xxxxxxxx...) {
//Run Code
}else {

is the unique code.)

Is there a way to transfer this unique code beforehand and then use the above code?

I am using PHP Version 5.6

Answer Source

To ensure that an end user has some sort of authority to do something, you need to use sessions. For better security, you need to use https instead of http. That makes it far more difficult to steal the session key. Stealing a random code from JavaScript is trivial compared to stealing a session key.

Doing this is very simple...

if($_SESSION['authorized']) // the user can do the secret stuff
else // the user cannot do the secret stuff

Setting the user to be authorized is just as simple...

$_SESSION['authorized'] = true;

That's all there is to it. Once you start a session, the variables in the $_SESSION array are, as best as you get it, tied to the end user.