Get PHP session variable with AJAX - php

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?

Related

php click out logged user with ajax

good afternoon from gmt+8 timezone.
I had built a login/system , now I want to implement a function that will click out users , so i make a status column in the db ,
2 types of values , lock => lock , active => not lock.
I can use crud method to update the status and output in a table. surely i cam lock the user , and status change to lock, that is working fine, but the problem is the locked user still has access the to system , since the session still valid , she/he has to close the browser or their session is terminated.
on the login page I check if user is lock then can login.
since the user still has access when the session still valid , I want to input ajax call the server to check the status on setInterval.
on backend php: check if user is lock , terminate the session , give alerts box and redirect.
but the issue now is my code is not working, here are my ajax call , if I un-comment //console.log('success');, success will be kept in console.log , meaning the call is success.
<script>
function getUserStatus(){
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
});
}
setInterval(function(){
getUserStatus();
},3000);
</script>
on my ajax.php page , I make sure connection to db is working,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$admin_username = check_input($_POST['username']);
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clicked out');window.location.href='../index.php';</script>";
}
}
function to check user is lock
function isLocked($username){
global $connection ;
$query = "SELECT status FROM table where name = '$username' ";
$result = mysqli_query($connection,$query);
confirm($result);
while( $row = fetch_array($result)){
if($row['status'] == 'locked' ){
return true;
}else{
return false;
}
}
}
if i directly access ajax.php with the log user , below action is working .
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clickedout');window.location.href='../index.php';</script>"; }
not sure what is wrong with my codes and how to fix it ?
any assistance/suggestion would be highly appreciated .
your ajax.php echos something, that may be data, a json or in your case a js script.
The ajax calls ajax/ajax.php, if the http request succeeds it enters
success:
function(response){
//console.log('success');
}
so the variable response holds the output of that call to ajax/ajax.php. if you use
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
dataType: "script",
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
the value of "response" will be executed if it is a working script.(without tags)
further information you can find here:
http://api.jquery.com/jQuery.ajax/
without dataType: "script",in the call you could do something like that:
function(response){
//console.log('success');
$('#somediv').html(response);
}
that will insert the result in a div, if it is a well formated js script, it will be executed.

Refreshing a page with codeigniter after ajax click event

I have the following php codeigniter function code which is being called by a jquery ajax function:
$this->load->library('session');
$this->load->helper('url');
$ids = $_POST['i'];
$message = $_POST['m'];
var_dump($message);
var_dump($ids);
$sql = 'update replies set `response` = "'.$message.'" where id IN ('.implode( ',', $ids).')';
echo $sql;
R::exec($sql); // works normally to here
redirect($this->uri->uri_string());
I want to refresh the page after the db insertion of 'message'. however nothing seems to happen. everything works normally including the db insertion. What am I doing wrong?
You can not redirect via AJAX url. Redirect is possible using callback function in
three ways done, fail and always.
Example:
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
.done(function(url) { // echo url in "/path/to/file" url
// redirecting here if done
location.href = url;
})
.fail(function(url) { // echo url in "/path/to/file" url
// redirecting here if failed
location.href = url;
})
.always(function(url) { // echo url in "/path/to/file" url
// redirecting here always
location.href = url;
});
On your ajax success use this after showing success message
window.location="path_to redirect";
like for example i am redirecting to member controller
window.location="member";
Hope this helps.

Using jQuery and json to grab current user

I am working on a project and am stuck. I am new to jQuery and JSON and I want to grab the current logged in user. I am able to pull the all the information from the user table, but I just want the user name so I can display it. I want to eventually append the current user to a html element
js code
var getUser = function(){
$.ajax({
url: 'xhr/get_user.php',
type: 'get',
dataType: 'json',
success: function(response){
if(response.error){
console.log(response.error);
}else{
console.log(response);
//$('#current_user').append(response);
}
}
});
};
php code
<?php
// check if logged in
// per project or all tasks?
//
error_reporting(E_ALL);
session_start();
session_regenerate_id(false);
require_once("reqs/common.php");
require_once("reqs/pdo.php");
//require_once("reqs/auth.php");
checkLoggedIn();
$userID = param($_GET, 'userID', $_SESSION["user"]);
$dbh = new PDB();
$db = $dbh->db;
$user = $dbh->getUser($userID);
exitjson(array("user"=>$user));
?>
Just use $.getJSON
$.getJSON("xhr/get_user.php",function(userData){
console.log(userData);
}).fail(function(xhr,textStatus,err){
console.log("error",err);
});
And remember to add JSON type header to php respond.
An example of PHP:
header('Content-type: application/json');
echo json_encode($user);

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.)

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

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.

Categories