Reputation: 155
I'm working with a javascript file that makes an ajax call to a php file (a mail sender).
I don't want someone to build a bot that just calls the php page using the proper parameters, so I want one of the parameters to be a token string that the php can then compare to a string stored server-side.
So I made a php that creates a random string and saves it to storageSession, then echoes it.
My JS has an ajax call that runs that PHP file, in order to get the token... but for some reason, it doesn't.
Unfortunately, I can't write here from where I work, I cannot install chrome extensions (I'm not a programmer after all, just an editor who doesn't want to seed the website with the worst vulnerabilities out there) and I can't see the code from home.
I hope my memory is good.
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$String = '';
for ($i = 0; $i < 20; ++$i) {
$String .= $characters[rand(0, $charactersLength - 1)];
}
$_SESSION['token'] = $String;
echo $String;
}
var myId;
$ajax(token){
data: ''
type: 'text'
success{
myId=token;
console.log(myId);
}
the console shows "undefined". Why?
Upvotes: 1
Views: 11652
Reputation: 1
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$String = '';
for ($i = 0; $i < 20; ++$i) {
$String. = $characters[rand(0, $charactersLength - 1)];
}
$_SESSION['token'] = $String;
echo $String;
}
var myId;
$ajax(token) {
data: ''
type: 'text'
success {
myId = token;
console.log(myId);
}
}
Upvotes: 0
Reputation: 1237
$_SESSION
is an array. You must assign the variable this way :
$_SESSION['token'] = "myValue";
With []
not ()
. Also, don't forget to start your session on every page.
To generate a random token, if you are using PHP7, you may use random_bytes
Which leads to something like that :
$_SESSION['token'] = random_bytes(12);
The pseudo code your give make hard to understand what the actual code is. Can you please provide the exact code (except for the token generation if you want to keep it secret)?
Also, you should not try to implement your own security system, developers, even seniors, always fail at it. For example, you can use this library, done by known cryptographic people.
Upvotes: 4