Help with a php code to not show the page if it is accessed from the url

0

I have the following code that its function would be to detect the entry from the page step1.php to paso2.php

Let me explain, I want people who enter step2.php without going through the first step not to be allowed, with this code I have achieved it but I have a problem that is that it does not detect that I am entering from step1.php and I enter from any other page with a link to step2.php and log in normally when I should also send the error message

    <?php
$ref = $_SERVER['HTTP_REFERER'];
if(isset($ref[0])) {
    $protocol = strtolower(parse_url($ref)['scheme']) === 'https' ? 'https':'http';
    echo (strtolower($ref) === $protocol . '://paso1.php') ? 'welcome':'BIENVENIDO, EXITO';  
} else {
   echo 'ERROR HAS INGRESADO POR URL O NO HAS INGRESADO DESDE PASO1.PHP';
}
   ?>

I would like the browser to act in this way: (1) if you enter by step1.php IF I allow you to enter (2) If you enter by URL I do NOT allow you to enter (3) If you enter a link from another page other than step1.php I DO NOT allow you to enter.

/// everything works except the (3)

    
asked by jkjul 18.08.2018 в 15:52
source

1 answer

1

It's very simple. You can place a form with a input hidden as verification data:

<form action="paso2.php" method="POST">
<input type="hidden" name="paso1">
<button type="submit">Enviar</button>
</form>

And on your page paso2.php you check that this input is being sent (you can change the name of "paso1" to which you want and you must place the same on the page paso2.php ). On the page paso2.php we only check that this POST is arriving and we put at the beginning of all this code:

<?php 
    //Aquí se comprueba que venga de paso1.php
    if(!isset($_POST["paso1"])){
       //Cualquier acción en caso de que no venga de paso1.php
        echo "Solo se puede acceder por paso1.php";
        die();
    }else{
        echo "Entró desde paso1.php";
    }
?>

To check if it comes from a specific url you just have to put this in your file paso2.php at the beginning of the file:

<?php
    $carpeta = str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname($_SERVER['SCRIPT_FILENAME']));
    $ruta = "https://$_SERVER[HTTP_HOST]$carpeta/paso1.php";
    $aux = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
    $referer = substr($aux, 0, strpos($aux, '?'));

    if($referer !== $ruta){
            echo "Solo se puede acceder por paso1.php";
            die();
        }else{
            echo "Entró desde paso1.php";
        }
    ?>

The route has to be something like this:

http://localhost/folder/paso1.php
    
answered by 18.08.2018 / 16:21
source