Reputation: 277
I have a question about Safety. I have a Javascript variable:
var toSearch = "something"
I want to send this variable to another php page. I'm using sessions: <?php session_start(); ?>
From what I've read I need to use a AJAX GET/POST procedure to pass this javascript client side variable to PHP server side.
I know it's possible to do this with:
window.location.href = "myphpfile.php?name=" + javascriptVariable;
then $_GET['name']
the variable. I've read that this isn't safe? Is it?
Upvotes: 4
Views: 522
Reputation: 6771
If you are not good with JavaScript or Ajax requests, I suggest the jquery .ajax method. jQuery is really well-documented and great for beginners.
Also, your variable is not set properly. Should be:
var toSearch = "something";
So visit: http://api.jquery.com/jQuery.ajax/ to get started.
A sample of how to do this.
JS:
function myFunction() {
var toSearch = "something";
$.ajax({
url: 'mysite/action_page.php?toSearch=' + toSearch,
success: function(data) {
alert('Here is some data from the $_GET request: ' + data);
}
});
}
PHP:
<?php
/**
* I strongly suggest a security measure here
* ie: if($_GET['token'] != $_SESSION['token']) die('access not permitted');
*/
//init
$search_string = '';
//set
$search_string = htmlspecialchars(trim($_GET['toString']), ENT_QUOTES);
//TAKE A LOOK AT PHP.net IF YOU DON'T KNOW WHAT THE TWO METHODS ABOVE DO.
// will help prevent xss
echo $search_string;
//all done!
?>
Upvotes: -1
Reputation: 6469
Well the better solution would be to go with an ajax request if you dont want to force page reload. regarding security its the same hence every user can manipulate querystrings with ease... we have an address bar for this :)
window.XMLHttpRequest = window.XMLHttpRequest || window.ActiveXObject('MSXML2.XMLHTTP') || window.ActiveXObject('Microsoft.XMLHTTP');
var ajax = new XMLHttpRequest();
ajax.open('get', 'page.php?name=' + javascriptVariable, true);
if ( ajax.readyState == 4 && ajax.status == 200 )
{
// ajax.responseText is the result from php server
// ajax.responseXML is the result from php server
}
ajax.send(null);
Upvotes: 1
Reputation: 324650
It's only unsafe depending on what you do with it. Anyone can type whatever they like in the address bar, and you have no control over that. For instance, I could go to
http://example.com/myphpfile.php?name=fuzzball
Now, that's not a danger in itself, but if I were to put some MySQL code and you were placing this directly in a MySQL database with no sanitisation, then it's dangerous. If I put in HTML which you then display to other users, then it's dangerous.
All you have to do is remember that while GET and POST aren't dangerous, they cannot be trusted to be what you expect them to be, therefore you should make sure that they are on the server side, where it can be trusted.
Upvotes: 2