I'm new to Ajax and PHP in general. So far, I managed to make an Ajax call to my PHP script which fetches data from my database. However, upon testing, I realized that, even if I'm not logged in, I can still access and run the PHP script directly and when that happens, it populates all the data from my table, which I don't want to happen.
Now based on that I see a major security issue where anyone can access and run the script and see user information.
Now I'm not familiar with security and stuff in PHP, kinda new to it. My question is how would I go about to make the script unaccessible directly, or only when the admin is logged in it could be accessible?
I read around that I could check the session, I tried but it didn't work for some reason. So I'll put what I coded below.
Here's the PHP which fetches data, getData.php:
<?php
session_start();
if(isset($_SESSION['id']) && isset($_SESSION['name']) && isset($_SESSION['admin']) && ($_SESSION['admin']==1)){
include_once('config.php');
//Create PDO Object
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//Set Error Handling for PDO
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Query
$sql = "SELECT users.name, users.email, users.admin, stores.admin, stores.name FROM users INNER JOIN stores ON users.id=stores.admin";
//Prepare Statement
$stmt = $con->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch()){
echo '<tr>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>**********</td>';
if($row[2] == 1){
echo '<td>Yes</td>';
}elseif ($row[2] == 0) {
echo '<td>No</td>';
}
echo '</tr>';
}
$con = null;
}
?>
Here's the ajax that does the call to get the data. It's just a snippet, but it's part of a bigger thing(button on click to be precise), myAjax.js:
$.ajax({ //create an ajax request to getData.php
type: "GET",
url: "includes/getData.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#userInfo > tbody").html("<pre>"+response+"</pre>");
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
Finally, this I set the following sessions, when user logs in:
$_SESSION['id']
$_SESSION['name']
$_SESSION['admin']
$_SESSION['admin'] == 1 means the user is an admin. Otherwise it's not.
Any help is greatly appreciated.
Edit:
Forgot to include what I tried to check the session. I update the PHP.
Thanks
if( $_SESSION['admin']==1 ){ /* code */ }perhaps as one basic optionif(isset($_SESSION['id']) && isset($_SESSION['name']) && isset($_SESSION['admin']) && ($_SESSION['admin']==1)){and when I did that, no data would show. So I'm not sure what's wrong.