Is it possible to prohibit access to PHP documents from URLS?

0

I have .php files that make includes of other files, and AJAX scripts that need to make requests to other .php documents.

For example, Document X.php has an AJAX script that sends a request to a B.php document and brings some information. Obviously, being ajax with what is being worked on, the route it points to can be seen from the source code, and anyone who sees the route and accesses it will receive the information that ajax returns.

In these cases, as ajax sends a request with form data, I can see if that request is empty or not with isset and depending on that return the content or not show it.

However, I also have AJAX scripts that only bring information from an .php file. That is, the file in question goes to a database, and gets a score, and that score I bring it to ajax and I put it in a DIV. But here there is no request for a form, so I can not think of what I could do to show it only through ajax and not if you enter the page in question.

I give an example:

      <!-- Funcion para AJAX -->
  <script>
  $(document).on('ready',function(){
    $('#boton').click(function(){
      $.ajax({
         type: "POST",
         url: "Reto.php",
         data: $("#form").serialize(),
         success: function(data)
         {
           $('#Resultado').html(data);
         }
       });

       $.ajax({
          type: "POST",
          url: "../Nav/Act/Puntos.php",
          success: function(data2)
          {
            $('#act1').html(data2);
          }
        });

        $.ajax({
           type: "POST",
           url: "../Nav/Act/Errores.php",
           success: function(data3)
           {
             $('#act2').html(data3);
           }
         });
    });
  });
  </script>
  <!-- Fin -->

The first request sends information $ _ POST ['value1'] etc ... So to prohibit or not access through URLS, I simply verify that this array is not empty, and if it is I deny the data.

But what about the other two AJAX requests? They are not sending data by any form, they are simply extracting data from some documents .php

One solution I can think of is to have hidden forms, but I see it very sloppy.

I was also wondering if it is possible that the .php documents could have particularities such as classes, (private, public) so that it can only be accessed by code and not by a URL. (Private methods can only be accessed by other methods, but not from the object).

Thanks for the help!

    
asked by Omar 12.05.2018 в 08:06
source

2 answers

1

This could be a possible solution, most requests Ajax should set this particular header that you can use to filter the requests Ajax and No Ajax . You can use this to help determine the type of response ( json / html ):

if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
    // Permitir acceso....
} else {
    // Ignorar....
} 

You can add it yourself on your own Ajax requests with the following in your JavaScript code:

var xhrobj = new XMLHttpRequest();
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 

In modern browsers, if you access a page using AJAX , PHP add this header to the request. If your page is called and if this header is not present, there is a good chance that it will be called directly (or redirected by another page through a hyperlink or otherwise). Basically, this always shows the forbidden page unless this page is called using AJAX .

if(!$_SERVER['HTTP_X_REQUESTED_WITH'])
{
   header("HTTP/1.0 403 Forbidden");
   exit;
}
  

Important Note: This is not 100% effective since the headers can be forged.

SO Source: Prevent Direct Access To File Called By ajax Function

    
answered by 12.05.2018 в 14:59
1

For both forms and ajax, the way to limit access is to generate a "Token", save it in a session, print it in the HTML and use it every time a request is made.

In this link you can see several ways to implement it link

I'll copy here the simplest:

paginaConForms.php

<?php 
session_start();
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];
?>

<input type="hidden" name="token" value="<?php $token' ?>" />

phpQueRetornaAjax.php

if (!empty($_POST['token'])) {
    if (hash_equals($_SESSION['token'], $_POST['token'])) {
         // Procesar el Form/Petición
    } else {
         // Enviar a un log el intento, enviar datos falsos o error
    }
}

In the case of pages with only javascript you can put a hidden form, or capture the value to send with $('input[name=token]').val();

You can generate a token for each form, for each ajax call, give them an expiration time, etc ..

    
answered by 12.05.2018 в 20:23