tags:

views:

285

answers:

3

I currently have a javascript file 'score.js' which makes use of jQuery.js, which is being called correctly via a link. The code in score.js is:

function originalUpdateScore(answer,correct){
if (answer == correct) 
{    
$.post('updateScore.php');  
}
window.location.reload(true);
}

This function calls 'updateScore.php':

<?php
include("dbstuff.inc");
$con = mysqli_connect($host, $user, $passwd, $dbname)
or die ("Query died: connection");  

$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1
 WHERE (user.Username='$_SESSION[logname]')";

mysqli_query($con, $updateScore);

?>

However the database is not being updated correctly. If I replace the line:

$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1 
               WHERE (user.Username='$_SESSION[logname]')";

with:

$updateScore = "UPDATE `user` SET `tempScore`=`tempScore`+1 
               WHERE (user.Username='123pf')";

Where 123pf is the value that the SESSION variable contains in the php file calling the javascript it updates correctly. Why does using the session variable not work? Am I calling it incorrectly in the query?

Thanks in advance.

+5  A: 

Are you calling session_start anywhere inside updateScore.php?

If you haven't started the session I do not believe that session variables will be available.

Paolo Bergantino
Thanks for ypur response....can't believe it was something as simple as that! Thank you.
+1  A: 

also, do you have complete control over $_SESSION['logname']? If not, someone could easily change their logname to inject SQL and damage/compromise your database. For example, if they were able to set their logname to be this, you could lose your user table:

$_SESSION['logname']="'; DROP TABLE user;-- ";

You're opening yourself right up to cheaters by playing like this. Under this scenario, any user could visit updateScore.php at any time to increase their stats, since that script neither checks their answer nor checks for a token that the JS builds to say the score is ok. It is a bad idea to keep this kind of logic on the front-end (javascript) without also having it verified on the back end (PHP); javascript & AJAX are very helpful shortcuts that can improve user experience, but they cannot be trusted as sole validity checkers.

yaauie
Thanks for your response, $_SESSION['logname'] is controlled elsewhere, I will work on my code to try and address the issues you have mentioned.
A: 

It's probably just a transcription error, but the code that you have shown in your question uses $_SESSION[logname], it should be $_SESSION['logname'].

Julian