Jump to content

Sessions in Javascript?


BellQuestWars

Recommended Posts

Is there any way to access PHP session variables using Javascript?

If not, can I do something like this to edit a PHP variable:

<?php echo $x ?> = $x

I dont know AJAX, and am having a hard time learning it, so for right now I'm using php to access the database, then transferring those values to JavaScript. If anyone is willing to give me a straightforward tutorial (connecting to mysql, editing info in tables, etc.) then I will learn, but as of now I havent found any.

Link to comment
Share on other sites

You connect to the database using PHP. Never run a query on your database from a user input or your website will be hacked right away. To change the session variable, simple call a php page that will change the session variable to whatever you want (directly or via ajax).

Link to comment
Share on other sites

You connect to the database using PHP. Never run a query on your database from a user input or your website will be hacked right away. To change the session variable, simple call a php page that will change the session variable to whatever you want (directly or via ajax).

 

Databases are queried via user input all the time.  What do you think a user registration form ultimately does?  Or when data is retrieved based on a GET value?  The key is in sanitizing the input.

 

To the OP: If you don't want to use ajax to stop the page from refreshing, just use a PHP session.  Sessions can work even when it's just one page refreshing over and over.  Then it's just a matter of:

 

var myVar = <?php echo $_SESSION['myVar']; ?>;

 

For ajax, hardly anyone writes raw ajax any longer.  Take a look at jQuery's ajax functions, especially $.get() and $.post().

Link to comment
Share on other sites

Databases are queried via user input all the time.  What do you think a user registration form ultimately does?  Or when data is retrieved based on a GET value?  The key is in sanitizing the input.

Yes, but the data is validated and filtered before you store them in the database and the actual query happens in the backend. I've seen open source project where they use something like this

ajax.query("update `sometable` set `something` = 'something'");

on the front end javascript code. As you can see, that's a huge security risk. All I ment is to never run an actual sql query from a user input. Collect the parts you need for the query, validate, filter and run it in the backend.

Link to comment
Share on other sites

You connect to the database using PHP. Never run a query on your database from a user input or your website will be hacked right away. To change the session variable, simple call a php page that will change the session variable to whatever you want (directly or via ajax).

 

Databases are queried via user input all the time.  What do you think a user registration form ultimately does?  Or when data is retrieved based on a GET value?  The key is in sanitizing the input.

 

To the OP: If you don't want to use ajax to stop the page from refreshing, just use a PHP session.  Sessions can work even when it's just one page refreshing over and over.  Then it's just a matter of:

 

var myVar = <?php echo $_SESSION['myVar']; ?>;

 

For ajax, hardly anyone writes raw ajax any longer.  Take a look at jQuery's ajax functions, especially $.get() and $.post().

 

Okay, thanks, but I need to change a session variable from within a javascript.  Heres what I need to do:

Player loads the page, they get their X and Y coordinates from a database.

The player moves. When the player moves, their X and Y coordinates change. This must then change in the database.

The player may then load the page again, and their X and Y will be saved.

Problem isnt getting the variables from the database, the problem is updating it. I'm having a hard time learning AJAX. Can I simply run something like

ajax.query("MYSQL QUERY HERE");

And then come up with some security things when I need to start worrying?

Link to comment
Share on other sites

Here is a very simple ajax request. If you are building a game and don't know how to do this, you might want to consider hiring someone.

// call the ajax request by using update_xy(New X, New Y);

function update_xy(x, y){
// make sure to validate the x and y values in your php page
var url = 'my_page.php?X='+x+'&Y='+y;

var xhr = new XMLHttpRequest();
this.privates.xhr.open("GET", url, true);
xhr.send(null);
}

Not tested

Link to comment
Share on other sites

Can anyone point me to a good AJAX tutorial? I really want to learn how to use AJAX with MySQL, but I dont know how.

 

Instead of trying to do AJAX in the raw, you should look at using jQuery for your AJAX needs.  It'll save you from having to worry about the technical boilerplate code, and allow you to focus on what you actually want to do.

Link to comment
Share on other sites

Okay, I looked up jquery, and Installed it onto my webpage.

How would I go about updating a MySql table using Jquery? Is there a function for updating and reading MySql tables?

 

...

 

It seems like you don't actually know what AJAX is.

 

In short, AJAX is when you have JavaScript send a request to a server side script.  In this case, it would be your PHP script.  The request sent is just a normal GET or POST request.  Your PHP script would process this request just like it normally would if no JavaScript was being used, and then return the result.  With AJAX, JavaScript captures that result, which it can then place anywhere in your site.

 

Because AJAX starts and ends with JavaScript, it has no knowledge of anything on the back end.  This means it has no idea about databases.  All that's really going on is JavaScript acting like a bridge between your back end script and what's being displayed on the screen.

 

So, to update a table using AJAX (not just jQuery in particular), you'd do the same things that you'd normally do on the PHP side (taking $_GET or $_POST data, running the query, etc.).  When you return the result, you'd most likely want to encode it as JSON (JavaScript Object Notation - PHP has a built-in function for that: json_encode)*.  Then, in your JavaScript, you'd parse that JSON data and dynamically place it in your HTML through DOM functions (which jQuery also simplifies).

 

Read through the code examples on the jQuery site.  If those don't do the job, slow down and learn the basics of JavaScript and JSON.  They're core technologies for the web.

 

*If your result is a simple string message, like "Table updated," you don't need to encode it.

Link to comment
Share on other sites

Okay thanks. So from reading that, how a table would be updated I would have this code on one page:

 

xmlhttp.open("GET","update.php",true);

 

Then on update.php I would have what I would normally have if I was using a html form, such as:

    $result = mysql_query("UPDATE users SET x='$_GET[x]' WHERE username='$_SESSION[name]'") 

 

I'm guessing thats how it works, but it probably isnt.

Link to comment
Share on other sites

Okay thanks. So from reading that, how a table would be updated I would have this code on one page:

 

xmlhttp.open("GET","update.php",true);

 

Then on update.php I would have what I would normally have if I was using a html form, such as:

    $result = mysql_query("UPDATE users SET x='$_GET[x]' WHERE username='$_SESSION[name]'") 

 

I'm guessing thats how it works, but it probably isnt.

 

Oh wait, now I think I understand. I would have the

var url = 'update.php?X='+x+'&Y='+y;
xmlhttp.open("GET",url,true);
xmlhttp.send();

 

Then on the page update.php, I would have something like:

$x=$_GET["X"];
$y=$_GET["Y"];
$query = mysql_query("UPDATE users SET x = '$x'
WHERE user = '$_SESSION[user]'");
$query = mysql_query("UPDATE users SET y = '$y'
WHERE user = '$_SESSION[user]'");

I'm hoping that code will work. Just posting here first so I dont get frustrated from errors.

Link to comment
Share on other sites

Just a quick note, you might want to read up on mysql injection and security issues. It might sound like a lot, but it's pretty simple and will save you a lot of headaches in the future.

Link to comment
Share on other sites

Okay, This code isnt working:

 if (keyp == 56) {
p1y = -1; 
var url = 'update.php?X='+p1x+'&Y='+p1y;

var xhr = new XMLHttpRequest();
this.privates.xhr.open("GET", url, true);
xhr.send(null);
}  

This is the code that changes variables when the 8 key is pressed (up on the keypad) But for some reason, nothing happens when the key is pressed, except for the players movement.  Also if I go to the url mypage.com/update.php?x=3&y=3, it doesnt change the datbase.

Heres update.php:

session_start();
require_once("connect.php");
$x = $_GET[X];
$y = $_GET[Y];
mysql_query("UPDATE members SET x = '$x' WHERE username = '$_SESSION[username]'");
mysql_query("UPDATE members SET y = '$y' WHERE username = '$_SESSION[username]'");
?>

Link to comment
Share on other sites

Okay, I have it down. Now how would I make it display all players that are online and on a specific room? Would I do something like in a page called showplayers.php put:

<?php
require_once("connect.php");
session_start()
$map = $_GET[map]
$results = mysql_query("SELECT * FROM members WHERE online='true' AND map='$map'");

 

I dont know what else I would put to get each players X and Y? I would call this page every time the player moves,  but then how would I go about displaying the players? I'm stumped on this one.

Link to comment
Share on other sites

Sorry, back tracking a little...

 

Yes, but the data is validated and filtered before you store them in the database and the actual query happens in the backend. I've seen open source project where they use something like this

ajax.query("update `sometable` set `something` = 'something'");

on the front end javascript code. As you can see, that's a huge security risk. All I ment is to never run an actual sql query from a user input. Collect the parts you need for the query, validate, filter and run it in the backend.

 

Have any examples of this? I've never seen it. They must have been using a plug-in that connects to a PHP script or something, because JavaScript simply can't query a database directly, and jQuery certainly doesn't natively support it as a result.

Link to comment
Share on other sites

Sorry, back tracking a little...

 

Yes, but the data is validated and filtered before you store them in the database and the actual query happens in the backend. I've seen open source project where they use something like this

ajax.query("update `sometable` set `something` = 'something'");

on the front end javascript code. As you can see, that's a huge security risk. All I ment is to never run an actual sql query from a user input. Collect the parts you need for the query, validate, filter and run it in the backend.

 

Have any examples of this? I've never seen it. They must have been using a plug-in that connects to a PHP script or something, because JavaScript simply can't query a database directly, and jQuery certainly doesn't natively support it as a result.

 

That function looks like it's simply passing an entire db query to PHP via POST.  Which, if something like that actually exists, is beyond dumb.

Link to comment
Share on other sites

Yes, the function pass the entire query into a php via post and some scripts out there actually do some dumb stuff like that. A few years ago someone asked me to check why his video sharing website database was wiped clean. After reviewing the code, I found that the script was creating the mysql query in javascript and passing them into php via post. With so many scripts out there, there is always someone who contributes unsecure code without knowing the problems it can cause.

Link to comment
Share on other sites

I think I have the displaying of other players figured out, but I cant really test it until my host puts website back on (they check for malicious content 2 days after you open a website, and that takes about 2 days.)

 

You should look into setting up a LAMP stack for your local machine.  Far more efficient than FTPing your files over and over again.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.