Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

82
Visualizações
Prevent Direct access to PHP file using AJAX

I want to prevent direct access to a certain PHP file called prevented.php My logic is that I have a main file lets call it index.php and it generates a token and stores it in a $_SESSION variable. I also have a another file called def.php which is called using AJAX and it passes the token from the index.php to the def.php and if the $_SESSION['token'] is equal to the $_POST['token'] it defines a _DEFVAR and returns true otherwise it returns false. After I called the def.php and it returns true, I redirect to the prevented.php via javascript using location.href="prevented.php". In the top of the prevented.php file there is a code which checks if the _DEFVAR is defined or not. If not, its die with a message like invalid otherwise it displays the content of the prevented.php file. But somewhy I always get invalid message and I don't know why. Any idea how to reach the prevented.php without directly direct the page?

Here's my code:

index.php

<?php
  $_SESSION["token"] = hash_hmac('sha256', "tokenString", "t2o0k0e0n3"); // Creates a hashed token
?>
<script>
    $.ajax({
      type: "POST",
      url: "def.php",
      data: {
         token: '<?php echo $_SESSION["token"]; ?>'
      },
      cache: false,
      success: function(data) {
          console.log (data);
          if (data) {
            console.log (data + ' valid');
          } else {
            console.log (data + ' invalid');
          }
          location.href = "prevented.php";
      },
      error: function () {
        console.log('error');
      }
   });
</script>

def.php

<?php
    session_start();
    if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token']) {    
       echo false;
       die('invalid in def');
    } else {
      define('_DEFVAR', 1);
      echo true;
      die ('valid in def');
    }
?>

prevented.php

<?php
   include "def.php";
   if (defined('_DEFVAR')) {
    die ('valid in prevented'); // instead of this I would show the content of the page
   } else {
       die ('invalid in prevented');
   }
?>
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your code is unnecessarily overcomplicated. If your intent is merely to ensure that visitors to protected.php have first visited index.php then all you need to do is create a session flag in one and check for its existence in the other. There is no need for any AJAX or any form POSTs. The innate behavior of PHP sessions already gives you this functionality.

index.php:

<?php
session_start();
$_SESSION['flag'] = true;
?>
<a href="protected.php">click here for the protected page</a>

protected.php:

<?php
session_start();
if ($_SESSION['flag'] ?? false) {
    echo "you have previously visited index.php";
} else {
    echo "you have not previously visited index.php";
}
?>
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda