How to send data between ajax and php in secure way? - php

I have index.php, ajax.js and process.php (where I get my AJAX data).
I am using AJAX this way:
var = $('user_id').val();
$.ajax({
url : "somefile.php",
method : "GET",
data : {'user_id' : user_id},
cache : false,
success : function(data) {
// do something with "data"
}
);
User_id I receive from PHP file:
<input value="<?php echo $user_id; ?>" id="user_id" />
What do I need to do for increasing security?

Following can be added, just for increasing security measures,
In PHP code
<input value="<?php echo base64_encode($user_id); ?>" id="user_id" />
In JS Code:
var = $('user_id').val();
$.ajax({
url : "somefile.php",
method : "POST",
data : {'user_id' : user_id},
cache : false,
success : function(data) {
// do something with "data"
}
);
In "somefile.php"
for getting the file use the $_POST method, if will only accept the variable posted by using POST method. This can be used:
if(isset($_POST['user_id']))
{
$user_id=$_POST['user_id']
$user_id=base64_decode($user_id);
//all functionality here
}
else
{
//shoot error message
}

I'd recommend you don't provide the userid to the client. Can you store it in a session variable instead?

If this user_id is being used to retrieve some confidential information related to the logged in user then that sounds like a security flaw.
You should be getting the user_id from a session variable

I think is not an good idea to put 'user_id' in client HTML and send back to server. You need to do more validation with data that sent from client (do some checking and filtering).
I recommend to use session instead of sending it to client, But you will have problem if editing two or more data at same time (multi tab), So you need to use session and some trick.
With this example your real user_id will never sent to the client.
index.php:
session_start();
$edit_session_id = md5(uniqid() . microtime(true));
$_SESSION['edit_' . $edit_session_id] = $user_id;
ajax.js:
var edit_session_id = $('#edit_session_id').val();
$.ajax({
url : "process.php",
method : "POST",
data : {'edit_session_id' : edit_session_id},
cache : false,
success : function(data) {
// do code
}
);
process.php:
session_start();
$edit_session_id = $_POST['edit_session_id'];
if(!isset($_SESSION['edit_' . $edit_session_id]))
{
die('Invalid edit session, please go back & refresh');
}
$user_id = $_SESSION['edit_' . $edit_session_id];
// Do something with user_id
//Clear the editing session
unset($_SESSION['edit_' . $edit_session_id]);

You should use POST instead of GET and you should also use ssl so that yuor urls sart with https instead of http.Now you are secured enough but you can increase security by adding extra encryption layer.

Related

PHP Variable in session not getting updated instantly

In two different php file one sets variable in session and other reads from it. while updated the second file gets the old value immediately after.
I have two consecutive jQuery ajax call from my page.
Tokens that fetch access token from remote server and set it in $_SESSION[token]. If it already finds a valid token in session does nothing.
/makeReq which calls another api with the token from $_SESSION[token]
I check if a session gets expired considering it's grant time and expiry. When it's expired it fetch and sets the new token in $_SESSION[token] but in the second call when reading from $_Session[token] it gets the old value.
These are two separate jQuery ajax call from a single page.
Below is the code for my token endpoint.
$current_time = time();
$get_new_token = true;
$request_token = null;
if (isset($_SESSION['token'])) {
$request_token = $_SESSION['token'];
$last_token_expire_time = $request_token['grant_time'] + $request_token['expires_in'] -600;
$get_new_token = $last_token_expire_time < $current_time ? true : false;
}
if ($get_new_token) {
$request_token=get_token();
$request_token['grant_time'] = time();
$_SESSION['token'] = $request_token;
}
Below is the code for my makeReq endpoint
$header=array(
'Content-Type:application/json',
'authorization:'.$_SESSION["token"],
'x-app-key:'.APP_KEY
);
Below is the code from where I am making the request
jQuery.ajax({
url: "'.plugin_dir_url( __FILE__ ) . "token.php".'",
type: "POST",
contentType: "application/json",
success: function (data) {
}
});
jQuery.ajax({
url: "'.plugin_dir_url( __FILE__ ) . "makeReq.php".'",
type:"POST",
data: {formData: postData},
success: function(data) {
}
});
Sounds like a cache issue.
Try to eliminate anything that may interfere with cache. If you are on a wp dedicated hosting, such as WpEngine, please note that they encourage not to use sessions at all.
Also, make you code with only the essential parts, just to see if you lose the session.

Get PHP session variable with AJAX

I am using the "Advanced Security PHP Register/Login System" which says you can get the SESSION id by using the following:
$userId = $_SESSION['user_id'];
I need to get the user_id into my front end using AJAX. My application has the following AJAX:
$.ajax({
url : 'login/get_user.php',
type : 'POST',
dataType : 'json',
success : function (result) {
alert(result['user']);
},
error : function () {
alert("error");
}
})
And the PHP script looks as follows (users.php):
<?php
$userId = $_SESSION['user_id'];
$return_data = array();
$return_data['user'] = $userId;
echo json_encode($return_data);
exit();
?>
But I only get "error" in my alert when I load the page. The user is signed in successfully using the system. Are the SESSION variables global? Where does the php script need to sit to access the user_id so that the AJAX can get the proper response?

Run javascript function then post for download

So I have a page where the user will hit the "export" button and I want to run a javascript function and get the data I need for the export and then call a php script to get the data from my database and force a download. Right now the problem is, I can run the javascript and then I call a post to my script, but nothing is downloaded. I am assuming it is because I am not actually moving the window to the php file, I am simply calling the script. can anyone help me out?
javascript: ids is an array that I need to pass to get the information. This is inside the function taht I call when the user hits the "export" button.
$.ajax({
type: "POST",
url: "exportLeads.php",
data: { 'idArray' : ids }
});
php: I used this Export to CSV via PHP quetsion. The function are implemented properly and I get no errors. There is just no file that is prompted for download.
$data = mysql_query($query) or die($query.mysql_error());
$results = array();
while($line = mysql_fetch_array($data, MYSQL_ASSOC)){
$results[] = $line;
}
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($results);
die();
You cannot download files with ajax. You can use window.location.href to redirect user to the file location, but whatever, i suggest you to read this, someone has a better answer for you :)
Download a file by jQuery.Ajax
or you can also use something like this
in your javascript
$.post( "exportLeads.php", { 'idArray' : ids }, function( response ) {
if ( response.error === 0 ) {
window.location.href = response.location;
}
}, "json" );
and in your php file
<?php
if ( $has_error ) {
echo json_encode( array( "error" => 1 ) );
}
else {
echo json_encode( array(
"error" => 0,
"location" => "link_to_file"
) );
}
?>
Got no time to write code, but in few words, you need:
Execute JS to call server side via ajax.
Generate file, put it to the server drive with some random name. Remember that name to session. Send some response to client.
When client gets response, redirect user with JS to some page where PHP code checks if there is some filename in session, and if there is, reads this file, deletes it and its name from session.
You could go for window.location.href in your success function:
$.ajax({
type: "POST",
dataType: "json",
url: "exportLeads.php",
data: { 'idArray' : ids },
success: function(data) {
if (data.success) window.location.href = "/link-to-your-download-script";
}
});
You would have to change the response to json_encode and split the functionality into two scripts, one for the export and one for the download script (with a unique id or sth.)

Get a PHP $_SESSION variable from Jquery?

I'm not yet a JSON/AJAX master so I don't know how to do this.
I need a $_SESSION['name'] PHP variable to work with in my jQuery stuff and I don't know how to access it... consider:
// the 'who is typing' shindig
$.ajax(
{
url: "whos_typing.html",
cache: false,
success: function(whos)
{
// here I need to access $_SESSION['name'] and do stuff with it
$("#soandso").html(whos); //Insert who's typing into the #soandso
}
});
You'll need to inject it, something like this:
var sessName = '<?php echo $_SESSION['name']?>';
The file containing this script must be executed by the php interpreter (i.e. a .php file)
EDIT: Conceding to Radu's point, it would be safer execute for unsanitized data:
var sessName = <?php echo json_encode($_SESSION['name']) ?>;
You need to use $.post to retrieve the variable from the server. You would have something like this:
$.post('echoMyVar.php', {post: 1}, function(data){
myVar = data['myVar'];
});
This is very basic, you first need to check if data is not null. In echoMyVar.php, you need just need basically the following:
header('Content: application/json', 1);
$returnVal = array('myVar', $_SESSION['myVar']);
echo json_encode($returnVal);
Again this is a shell, not secure, and would not handle any errors.
var name= "<?php echo $_SESSION['user_name'];?>"
will do it . . .
Remember php is a server side script, . . .so it takes precedence and get executed first and spits html to the client (Jquery , javacript) which will be executed in your browser . . . .
So, you can use server side variables to share with client . . . but not the other way around . . .
The easiest way is probably to include your javascript code in a .php file. Then you can simply do:
var phpVar = <?php echo $_SESSION['name']; ?>
SIMILAR POST
Server side in whos_typing.php:
<?php
//...
header('Content-Type: application/json');
echo json_encode(array(
'who'=>'Bob',
'session'=>$_SESSION,
// Be sure that you're not storing any sensitive data in $_SESSION.
// Better is to create an array with the data you need on client side:
// 'session'=>array('user_id'=>$_SESSION['user_id'], /*etc.*/),
));
exit(0);
Client side:
// the 'who is typing' shindig
$.ajax({
url: "whos_typing.php",
dataType: 'json',
cache: false,
success: function(data) {
var session = data.session,
who = data.who;
console.log(session.user_id); // deal with session
$("#soandso").html(who); //Insert who's typing into the #soandso
}
});
You need to echo the session variable from PHP when you send it to the browser. I'm assuming whos_typing.html is just the URL to a PHP script.

update .text() using ajax auto refresh

When I set the session in a file called signin.php:
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'array.php',
type: 'post',
data: {'user': $user}
});
";
In another file (index.php), I want to get:
<?php
session_start();
echo "log in as <span id=\"user\"></span><br/>";
$user = $_POST['user']
echo "
<script>
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
</script>
";
?>
I know I completely messed up with the code. What I want is that when the session is set in the signin.php file, I want $user in the content in "log in as $user" automatically updated without refresh the page, any help will be greatly appreciated!
First, work on diligently formatting your code more effectively. That code you posted was all over the place. This is a bad practice to get in and leads to errors, bugs, and other effects which can be difficult find due to the formatting.
If I follow what you're doing, when someone logs in and then hits the index.php page, you want to be able to load a user's information from another file that will give back the user data asynchronously?
signin.php
Your code is confusing in what it appears to be doing; you simply have not told us enough both in code and explanation to understand what the workflow entails.
For instance, in signin.php, you're echoing a <script> tag that does an $.ajax() request, but who/what get's this code? Is this part of the signin.php content, if the user successfully logs in? Does this mean the signin.php will load the page to use the $.ajax() here, or is that meant to run from the $.ajax() on success?
If it's the latter, you need to return regular Javascript with no markup (like a <script> tag wrapped around it) and use dataType: 'script' in the options.
Also, I would at least use a more descriptive word than array.php; if you're getting user data from it, name that file something like userdata.php.
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
dataType: 'script',
data: 'json=' + jQuery.serialize({user: '$user'})
});
";
Then in userdata.php, you can access it with $_POST['json'].
index.php
This honestly makes no sense:
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
);
Why is the setInterval() in an anonymous function that's run while setting $.text()? This is one of those What? moments, where I'm not even sure what you're trying to accomplish.
Before that though, you have:
$user = $_POST['user'] <<< Note here, you need a ; at the end
Why is this a $_POST? Does the signin.php use $_POST to log a user in? Here, I believe you want $_SESSION (I think, hope, ??), since that's where you stored the username when the user logged in using signin.php.
This is my best guess as to what you're trying to do (assuming you're returning JSON-formatted data):
<?php
session_start();
$user = $_SESSION['user'];
echo "log in as <span id=\"user\"></span><br/>";
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
data: 'json=' + jQuery.serialize({user:'$user'}),
dataType: 'json',
success: function(data){
$('#user').text(data.fullname);
}
});
</script>
";
?>
Try the following:
<?php
$user = 'john';
$_SESSION['user'] = $user;
?>
<script type="text/javascript">
$.ajax({
url: 'array.php',
type: 'post',
data: { 'user': <? echo json_encode($user) ?> }
});
</script>

Categories