PHP file requested by jQuery to respond only to the domain itself

Asked

Viewed 59 times

0

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

In PHP files where the request is made by .ajax() jQuery, there is the code 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 thus:

<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?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.