Javascript storing variable - javascript

I want to store some variable to the client side, currently, I have few selection (javascript variable, cookie, session), because I want to reduce the workload from the server, so the incoming parameter will not check on the server side.
For example,
Client side
<div id="showmoney"></div>
<script>
var money=10000;
$('#showmoney').html(money);
function changemoney()
{
{ pass the variable 'money' by ajax to php...}
}
</script>
PHP side
<?
$money = $_POST['money'];
$sql = "UPDATE user_details SET money = ".$money." WHERE uid = 123";
{ do query...}
?>
Are there any method make it more secure, because I afraid someone can modify the javascript variable by tools(firebug? if yes, how?)
thanks a lot~:)

Every variable that you do not want the user to change (such as a price tag) HAS to be stored on the server and not on the client. There are A LOT of ways to change what the client sends to you, and FireBug is just the simplest tool. More sophisticated tools will allow to intercept and edit every HTTP request..

Are there any method make it more secure, because I afraid someone can modify the javascript variable by tools(firebug? if yes, how?)
You can never, ever trust incoming data from the client. It can always be manipulated. Essential checks like prices you need to do on server side - a client side check is merely for the user's convenience.
Also, the code you show has a SQL injection vulnerability that you should sort out.

Anything you store in the client (browser) can be manipulated. The fix for your issue, is to verify that the information sent back to the server hasn't been tampered.

People can do just about anything to the page they want.
In the Google Chrome debugger (accessed with Ctrl+Shif+J) they could do the following in the console:
money = 10000000000000; //Or whatever arbitrary value they choose
changemoney();
As other people have said, never trust anything that people pass into the server from the client. The server needs to do a sanity check.

you have to align your desire to store something on the client for performance with the need for security. Sensitive info should only be on the server. Any savvy web user can tweak the javascript. Save bandwidth by putting other, less sensitive info on the client.

are you know about client side database storage the brand new API in HTML5. trying to find sollution with them. maybe helpful for you to save some data on client side.

Related

Set SESSION on php and remove it via JAVASCIPT [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

java session in servlet the same as sessionstorage in javascript

I have a servlet which I call the following:
request.getSession().setAttribute("name", nameObj);
Can I access it from the following page using
console.log('IH HERE' + sessionStorage.getItem('name') );
It doesn't seem to work. Either js or jquery solution would be nice.
Thanks,
Scott
This won't work, for two reasons:
sessionStorage is client-side only; it's not sent to the server via HTTP requests and the server can't write it without talking to the client.
request.getSession() is server-side only, with a session ID stored in a cookie but nothing else stored in a client-accessible format.
You'll have to use cookies if you want to achieve this effect (read / write by both) or loop over the session and provide it all in the page somewhere (read only by client).

Get values (a array) out a mysql database by opening a php file on a other host

This is wat needs to happen:
I need to get user information out a MySql database.
But i don't want to insert the password of my database in the php file. Because that file won't be hosted on my own server. Nobody must see that password when they access the server by ftp and edit the php file.
My first solution that didn't work was opening a php file from my own host and reading the output (i made a script that connects to the database and outputs a long string) and converted the output to an array by splitting the values.
This did not work because of security reasons in php.
I can't create a extra account for my database that has read-only access because my host won't allow me. (hostinger.co.uk)
I also thought about using a iFrame and load the file on my host. And read it using javascript to read it. But again, security won't allow me to edit it.
Does someone know a way to fix this?
OPTION 1:
Since you want to make sure your buddies server doesn't have access to the MySQL server info (username, password, etc), your safest bet is to connect to the database from your server, and just communicate between the two servers what needs to be retrieved.
As Darren mentioned in the comments, an API would do this just fine. Since there are a lot of open source libraries out there that can get the job done, I will recommend you one: pheanstalk
pheanstalk is a php client that works on top of the beanstalk library, which is basically a queue.
You could set up a queue on each server, and configure the communication to happen between the 2 servers. Then you would have worker.php scripts running every second (or 10 seconds or however so often you like) looking for commands being sent from 1 server, taking those commands in, processing them, and sending back the information to the main computer.
OPTION 2:
Instead of accessing your database, you can create a copy of yours, and have his server contain a copy.
Key points of option 2:
If his server isn't capable of carrying a full fledged MySQL database, there is MySQLi, which is very similar, but the only difference is that it is basically a file that you keep in your server. That is the benefit since it is LIGHT (hence the "i" from MySQLi). The downside is that the database isn't as "powerful", some operations might be limited, though that is to be expected, but good none the less.
If your friend has a database however, then better yet since it will have all the capabilities.
Now since I am assuming you would need to keep their copy of your database up-to-date, you can create a function that would send a request to your buddies server on what was updated. This is an API since it is intercommunication between processes behind the scenes, but probably wouldn't need any root access as some other API's might require.
Though the hastle here is that you would literally have to call that function every time you do any updates... :(
Edited:
OPTION 3
After talking a bit with the OP in the comments, another possibility came up. In his particular case, he might be willing to have a file in a public directory available for his buddies user to read. For example, lets say his file was located in:
http://www.example.com/hiddenfiles/dfjios4wr238##.txt
To access what is inside that file, you would have to know the name (and the name was specifically designed to work as a password, hence even though the information isn't sensative for the OP's specific situation, it's always best practice to stay consistent and think safe xD).
To access the file, the following could be done:
$path = 'http://www.example.com/hiddenfiles/dfjios4wr238##.txt';
$fileHandle = fopen($path, "r");
while ($line = fgets($fileHandle))
{
echo "--> {$line}";
}
fclose();

HTML hidden input shouldn't be editable

I just discovered a bug which I couldn't find any solution of, I would like your advise on that. Issue is there are a few hidden input types, which are there to store ID's of already saved data such as per person id if it is already saved etc. etc.
I just tried and change the value of that hidden variable manually, using google chrome and submit the form and surprisingly i did not get the id that should be there but instead i received the Id that I changed. for instance there was an value of 22 I change it 263 I received 263, whereas I should have be receiving 22. I want that 22 to come not that 263.
Its hard to explain I know but I have tried my level best to convey my issue please help and advise my on that how should I store some hidden value that are un-editable.
Any Idea?
Rule of Web Development #1: Never trust the client
Rule of Web Development #2: Never trust the client
Rule of Web Development #3: You can't make the client trustworthy
If the user shouldn't be able to edit it, never give it to them.
As others have said, there are a few ways to handle the situation. The most common is to use a SESSION variable on the server, available almost everywhere.
Store the "secret" values on the SESSION. They will be available when the user posts back.
You cannot control what data users put in HTTP requests to your server.
Instead, use authentication and authorization, on the server, when the request is received, to make sure that the user is allowed to submit the values they submit.
If you're wanting to keep track of data from one page to another I would use sessions. This is data that is tracked on the server.
//page one.php
$_SESSION['id'] = 22;
//page two.php
echo $_SESSION['id']; //22
This is a basic functionality of how browsers work - essentially someone could POST data pretending to be your form with whatever values they wanted in the fields - or even add extra fields.
If it's a problem consider moving that data from hidden fields to session variables.
If it's important for your hidden fields to be secure, don't contain them on the client-side. Client side variables are pretty easy to modify.
You should probably store them in your session, so they're not outputted to the client. If they're required on the page, use AJAX to grab them instead.
It kinda depends on the domain of your application, if it's in-house software then I wouldn't worry about it particularly.
It does not look like a bug.
What scares you about this? These fields are not going to be accessed and changed by your visitors. If you're afraid someone is going to hack the http request of your visitor and change his order (for example), then https connection should help.

Best way To handle a Cookie

i am newbie at developing web Application and like to learn best practices
i want to know what is the best practise to handle the cookie data should one use JavaScript or PHP to handle a cookie data?
1.Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
2.Do you use PHP to do all of the stuff?
3.Which one of the above will improve performance or is there another way?
should one use JavaScript or PHP to handle a cookie data?
To make this a little more general, let's call this "Client side" (which is almost exclusively JavaScript) and "Server side" (which can be PHP, JavaScript or any other language) code.
The short answer is that: It depends what you are doing with the cookie data.
Most of the time, dealing with cookies server side is simpler.
Sometimes, the information in the cookie needs to be secure, and you don't need to access it from client side code, so you'll set an http only flag on it so that if you suffer an XSS attack the damage is limited.
Sometimes you will want to avoid making a server round trip (to take a trivial example: You allow the user to pick different stylesheets for your website. You don't want to reload the entire page when their change their preference. You use client side code to change the stylesheet currently loaded, and client side code to store that preference in a cookie. In the future, when other pages are loaded, you can use server side code to set a different <link> element.)
Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
You might use client side code to set a cookie value, and then use server side code to read it. There is no point in using JavaScript to read it and then using some non-cookie based mechanism to send it to server side code. That just makes things complicated and more likely to go wrong.
Do you use PHP to do all of the stuff?
Only if all the stuff is better done with PHP
Which one of the above will improve performance or is there another way?
As is normal with questions of client side code vs server side code: If you aren't loading a new page anyway, then using client side code is usually faster.
It depends on the type of application.
If your application is full request based with PHP as backend, then use can PHP tot extract cookies.
check this link http://www.w3schools.com/php/php_cookies.asp
Or, if you application follows REST architecture or you want send data to the backend using Ajax. Then use javascript/Jquery to get cookie value and send it to the backend server that is PHP or in any other language.
Check this link to know, how to access cookies using jquey.cookie.js plugin:
https://github.com/carhartl/jquery-cookie
In handling cookies, it does not really matter whether you use javascript or PHP, it just depends on when it is more beneficial to access/manipulate them. Server-side stuff always seems more secure, but cookies are always accessible, client or server-side, so it doesn't really matter. You can create a cookie in PHP like this:
setcookie($cookieName, $cookieValue, time() + 3600);
That sets a cookie for an hour, you can then access it through the $_COOKIE superglobal array with array notation, for example
$var = $_COOKIE[$cookieName];
However, keep in mind that this won't work if cookies aren't enabled in the browser, such as when someone uses incognito mode.
In javascript, you can set cookies like this:
document.cookie="cookiename=cookievalue";
However, cookies in javascript are all concatenated as one big string in document.cookie, so the way to break them up into a normal array is with the split function, for example:
var arr = [];
function getCookieArray() {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
You can find more about that here http://www.w3schools.com/js/js_cookies.asp
So, remember, that cookies are not for storing sensitive data. They're often used to store preferences, but never anything that people shouldn't be able to have access to.

Categories