Block access to PHP pages with SESSION

0

I'm practicing PHP.

I'm setting up an admin panel with login screen.

I have my index.php page which is the login (EMAIL AND PASSWORD).

After logging in, go to admin.php page

The detail is that if the user enters www.seusite.com.br/administrativo.php, he accesses the page directly.

I have a valid page.php that creates level of access to users

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

    //Buscar na tabela usuario o usuário que corresponde com os dados digitado no formulário
    $result_usuario = "SELECT * FROM admin WHERE email = '$usuario' && senha = '$senha' LIMIT 1";
    $resultado_usuario = mysqli_query($con, $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'];
        $_SESSION['usuarioNome'] = $resultado['nome'];
        $_SESSION['usuarioNiveisAcessoId'] = $resultado['niveis_acesso_id'];
        $_SESSION['usuarioEmail'] = $resultado['email'];
        if($_SESSION['usuarioNiveisAcessoId'] == "1"){
            header("Location: administrativo.php");
        }elseif($_SESSION['usuarioNiveisAcessoId'] == "2"){
            header("Location: colaborador.php");
        }elseif($_SESSION['usuarioNiveisAcessoId'] == "3"){
            header("Location: cliente.php");
        }else{
            header("Location: index.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: index.php");
    }
        }
    else{
    $_SESSION['loginErro'] = "Usuário ou senha inválido";
    header("Location: index.php");
    }
?>

It works fine.

I tried to put this right after searching the information in the table

if (! isset($_SESSION["usuarioSenha"],$_SESSION["senha"])) 
//aqui pega o valor do nome do campo da pagina de login  echo
"<script>window.location='index.php'</script>"; 

// if it is not correct, it sends to the index page to log in again}

But it does not roll

This is my admin page.php

<?php 
    session_start(); 
?>
<html>
<head>
<link rel="stylesheet" href="css/style.css" type="text/css">
<title>Administração</title>    
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="js/javascriptpersonalizado.js"></script>
</head>
<body>
<div id="header">
<div class="conteudo">
<span style=" text-align: left; float: left; font-size: 20px; color: #000; line-height: 41px;">
Administração curriculos</span>
<div class="topo">

<?php

    echo "<span>Conectado como:</span> ". $_SESSION['usuarioNome']; 
?>

<br>
<a href="sair.php">Sair</a>
</div>
</div></div>

<div class="conteudo">
<form method="POST" id="form-pesquisa" action="">
            Buscar pelo nome: <input type="text" name="pesquisa" id="pesquisa" placeholder="Digite um nome">
            <input type="submit" name="enviar" value="Zerar pesquisa">
        </form>

        <ul class="resultado">
<?php
include("consulta.php");
?>
    </div>
</body>
</html>

Another one I have include (query.php)

    <?php    include("conecta.php");
// executa a consulta $sql = "SELECT * FROM usuario ORDER BY id"; $selec ="SELECT * FROM usuario WHERE destino"; $res = mysqli_query($con, $sql);   // conta o número de registros $total = mysqli_num_rows($res);
echo "<p>Resultados encontrados: " . $total . "</p>";   
// loop pelos registros while ($f = mysqli_fetch_array($res)) {
 echo "<p>" . $f['nome']. " | ". $f['email'] . " | ". $f['telefone']. " | "         . $f['destino']. " | ". "</p>"; }

    // fecha a conexão mysqli_close($con); ?>

What does the query in the database and displays a list of the records.

If I type in the browser www.seusite.com.br/consulta.php Access the direct page, I would like it if you enter it directly into the browser, direct it to the index.php if it is not logged in.

I have other pages that can only be accessed with login.

Can anyone help?

    
asked by anonymous 09.03.2017 / 18:46

3 answers

2

The use of <script>window.location='index.php'</script> for redirection is totally not recommended since simply deactivating the browser javascript is possible to access without any problem. Instead, modify the header before sending it to the browser via the header method of php:

header("Location: index.php");

Try changing the verification code for:

if (! isset($_SESSION["usuarioSenha"],$_SESSION["senha"])) 

To:

if (! isset($_SESSION["usuarioSenha"]) || isset($_SESSION["senha"]))
    
09.03.2017 / 20:07
0

I made this file called segrance.php, and I made the include.

<?php
    function seguranca_adm(){
        if((empty($_SESSION['usuarioId'])) || (empty($_SESSION['usuarioEmail'])) || (empty($_SESSION['usuarioNiveisAcessoId']))){       
            $_SESSION['loginErro'] = "Área restrita";
            header("Location: index.php");
        }else{
            if($_SESSION['usuarioNiveisAcessoId'] != "1"){
                $_SESSION['loginErro'] = "Área restrita";
                header("Location: index.php");
            }
        }
    }
?>
    
13.03.2017 / 18:33
0

If you want to block / redirect access to a page as you yourself explained by typing in the browser at www.blabla.com/administrativo.php. You have to block the GET method of accessing it by adding at the top of the page you want to block the following code:

<?PHP
$host = $_SERVER['REQUEST_METHOD'];
if ($host == 'GET') {
    header("Location: block.php");
}

Now, if access comes by entering the URL in the browser, the method is GET and you are redirecting to a block page, but if the user is on the authentication page, he accesses the administrative.php via POST method and the page will open normally.

    
13.03.2017 / 18:48