I'm building an API for my website and I only want the API to be accessible from my own website. The way I've built it is that I call a PHP file using ajax:
<?php session_start(); ?>
<script>
$.ajax({
type: "GET",
dataType: "json",
url: "secureapi.php",
data: "test="+document.cookie.substring(document.cookie.lastIndexOf('PHPSESSID')).replace(/phpsessid=/gi, '') + "userid=123",
success: function(response){
console.log(response);
}
});
</script>
In the PHP file I then check if it's called from a xmlhttprequest and that the session_id
is correct:
<?php
session_start();
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' AND $_POST['test'] == session_id()){
//QUERY DATABASE AND RETURN JSON
}
?>
Is this secure enough or can someone easily get the session_id
with CURL or something?