Block pages via url

Asked

Viewed 1,165 times

0

The restricted page is blocked for access via url, but I want to leave the warning on the login screen. For example: when you type the address of the.php corporate page in the url, the system directs you to the login screen and displays the LOGIN TO LOGIN message below the form. It follows below all the code.

Login

    <?php
    session_start();
    ?>
    <!doctype html>
    <form method="POST" action="login/valida.php">
        <h2>Área Restrita</h2>
    <label>Login</label>
        <input name="email_cli" type="email" autofocus required placeholder="Email">
    <label>Senha</label>
        <input type="password" name="senha_cli" placeholder="Senha (seu CPF)" required maxlength="11"><br>
        <button type="submit" class="botao_cadastro">Acessar</button>
    </form>
    <h4 style="color: red">
        <?php if(isset($_SESSION['loginErro'])){
            echo $_SESSION['loginErro'];
            unset($_SESSION['loginErro']);
        }?>
    </h4>
    <h4 style="color: green">
        <?php 
        if(isset($_SESSION['logindeslogado'])){
            echo $_SESSION['logindeslogado'];
            unset($_SESSION['logindeslogado']);
        }
        ?>
    </h4>
    <?php
    // Aqui ficaria sua mensagem, por exemplo
    if (isset($_SESSION['erro_acesso'])) {
    ?>
    <h4>Faça o login para acessar.</h4>
    <?php
    }
    ?>
    </html>

valida.php

    <?php
    session_start(); 
    //Incluindo a conexão com banco de dados   
    include_once("conexao.php");    
    //O campo usuário e senha preenchido entra no if para validar
    if((isset($_POST['email_cli'])) && (isset($_POST['senha_cli']))){
    $usuario = mysqli_real_escape_string($conn, $_POST['email_cli']); 
    //Escapar de caracteres especiais, como aspas, prevenindo SQL injection
    $senha = mysqli_real_escape_string($conn, $_POST['senha_cli']);
    $senha = md5($senha);

    //Buscar na tabela usuario o usuário que corresponde com os dados digitado no formulário
    $result_usuario = "SELECT * FROM clientes WHERE email_cli = '$usuario' && senha_cli = '$senha' LIMIT 1";
    $resultado_usuario = mysqli_query($conn, $result_usuario);
    $resultado = mysqli_fetch_assoc($resultado_usuario);

    //Encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
    if(isset($resultado)){
        $_SESSION['usuarioId'] = $resultado['id_cli'];
        $_SESSION['usuarioNome'] = $resultado['nome_cli'];
        $_SESSION['usuarioNiveisAcessoId'] = $resultado['nivel'];
        $_SESSION['usuarioEmail'] = $resultado['email_cli'];
        if($_SESSION['usuarioNiveisAcessoId'] == "1"){
            header("Location: ../basico.php");
        }elseif($_SESSION['usuarioNiveisAcessoId'] == "2"){
            header("Location: ../profissional.php");
        }elseif($_SESSION['usuarioNiveisAcessoId'] == "3"){
            header("Location: ../avancado.php");
        }elseif($_SESSION['usuarioNiveisAcessoId'] == "4"){
            header("Location: ../empresarial.php");
        }else{
            $_SESSION['erro_acesso'] = "Faça o login para acessar";
            header("Location: ../login.php");
        }
       //Não foi encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
       //redireciona o usuario para a página de login
       }else{    
        //Váriavel global recebendo a mensagem de erro
        $_SESSION['loginErro'] = "Usuário ou senha Inválido";
        header("Location: ../login.php");
        }
    //O campo usuário e senha não preenchido entra no else e redireciona o usuário para a página de login
    }else{
    $_SESSION['loginErro'] = "Usuário ou senha inválido";
    header("Location: ../login.php");
    };
    ?>

php connection.

    <?php

$servidor = "localhost";
$usuario = "root";
$senha = "";
$dbname = "clientes_db";

//Criar a conexao
$conn = mysqli_connect($servidor, $usuario, $senha, $dbname);

if(!$conn){
    die("Falha na conexao: " . mysqli_connect_error());
}else{
    //echo "Conexao realizada com sucesso";
}      
?>

verifi_access.php

    <?php
    session_start();
    function verifica_nivel($nivel_de_acesso) {
    if (!isset($_SESSION['usuarioNiveisAcessoId']) || $_SESSION['usuarioNiveisAcessoId'] != $nivel_de_acesso) {
    $_SESSION['erro_acesso'] = 1;
    header('Location: ../login.php');
    exit();
    }
    }
    ?>
  • Do you want to block direct access to a file by the url? for example: you have a connection.class.php and you don’t want the user to directly access the file?

  • Yes. The site is simple and the content is not something to worry about. I just want to prevent it from being accessed by the url.

  • I will publish the reply;

2 answers

3


From what I understand, you could use his level of access to not access certain types of files.

Editing code as you edit the question.

verifi_access.php

session_start();
function verifica_nivel($nivel_de_acesso) {
    if (!isset($_SESSION['usuarioNiveisAcessoId']) || $_SESSION['usuarioNiveisAcessoId'] != $nivel_de_acesso) {
        $_SESSION['erro_acesso'] = 1;
        header('Location: login.php');
        exit();
    }
}

Place at the beginning of the pages where you want to check if the access level is allowed for the area.

Using in php enterprise.

include_once "verifica_acesso.php";
verifica_nivel(4);

In the login.php would look something like this:

<?php
session_start();
?>
<!doctype html>
<form method="POST" action="login/valida.php">
<h2>Área Restrita</h2>
<?php
// Aqui ficaria sua mensagem, por exemplo
if (isset($_SESSION['erro_acesso'])) {
?>
<h4>Faça o login para acessar.</h4>
<?php
}
?>
<label>Login</label>
<input name="email_cli" type="email" autofocus required placeholder="Email">
<label>Senha</label>
<input type="password" name="senha_cli" placeholder="Senha (seu CPF)" required maxlength="11"><br>
<button type="submit" class="botao_cadastro">Acessar</button>
</form>
<h4 style="color: red">
<?php if(isset($_SESSION['loginErro'])){
echo $_SESSION['loginErro'];
unset($_SESSION['loginErro']);
}
?>
</h4>
<h4 style="color: green">
<?php 
if(isset($_SESSION['logindeslogado'])){
echo $_SESSION['logindeslogado'];
unset($_SESSION['logindeslogado']);
}
?>
</h4>
<h4 style="color: green">
<?php 
if(isset($_SESSION['restrito'])){
echo $_SESSION['restrito'];
unset($_SESSION['restrito']);
}
?>
</h4>
</html>

And in the valida.php after confirmation of existence of user and correct password:

if (isset($_SESSION['erro_acesso'])) {
    unset($_SESSION['erro_acesso']);
}

I hope I’ve helped.

  • I think this is exactly what he wants... good Hiago

  • Thiago. Helped me too much. Now I would like to implement it. I will change the question.

  • I edited the reply @Turkish. Valeu Guilherme!

  • Thiago. Returns the white page and does not redirect. It will be some array error?

  • @Turkish you are putting the header correctly, this way: header("Location: ../login.php"); ? 'Cause in my code it was just to illustrate.

  • Yes... I did. Until if I was wrong it would give error 404, only that it remains on the corporate page.php but with the white screen.

  • @Weird Turkish, I did the tests here and it worked perfectly. It just gives this problem in the business area?

  • On every page. I changed the code of how it is.

  • I did some more tests and did not find the error. I could post the code of the business area to take a look?

Show 4 more comments

0

Try this code:

$Page_Request = strtolower(basename($_SERVER['REQUEST_URI']));
$Page_File = strtolower(basename(__FILE__));
if ($Page_Request == $Page_File)
{
    exit("Acesso negado.");
} else {
   return true;
}

Or you can use a header for home.

I hope I’ve helped.

  • It blocked access via url, but also blocked when trying to login.

  • 1

    I made an issue try, if the return true not working try return $page_file. Or else use .htaccess to do this :(

  • Neither of the two worked. I’ll try with . htaccess and put the result. Thanks.

Browser other questions tagged

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