PHP file requested by jQuery respond only to the domain itself

0

I made a .ajax() of jQuery code to avoid direct access to PHP files, but would like to improve the security of requested PHP files, read about Access-Control-Allow-Origin and other tips, but I researched and did not get an explanation / code sample clearly.

In PHP files where the request is made by .ajax() of jQuery, the code exists at the beginning to avoid direct access:

<?php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

if(!IS_AJAX) {die('Acesso restrito');}

$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));

if($pos===false)
  die('Acesso restrito');
?>

The request is made as follows:

<button class='btn btn-default' id='btnGravarRegistro'>Gravar</button>

<script>
    $(document).ready(function(){
        $("#btnGravarRegistro").on('click', function(){
            $.ajax({
            type:'POST', 
            url: "ajax/cadastro",
            data: $('#formCad').serialize(),
            success: function(data) {
                $('#return').html(data);
            }
    });
</script>

How to improve validations to avoid direct access and code injection?

    
asked by anonymous 12.12.2017 / 00:22

0 answers