Block access to PHP pages with SESSION

Asked

Viewed 2,846 times

0

I am 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, direct the administrative page.php

The detail is that if the user type www.seusite.com.br/admin.php, he goes straight to the page.

I have a valida.php page that creates user access level

<?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 well that.

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 doesn’t happen

This is my administrative 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 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); ?>

That makes the query in the bank and displays a list of registrations.

If I type in the browser www.seusite.com.br/query.php Go to the direct page, I would like if it type this directly in the browser to direct it to index.php if it is not logged in.

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

someone can help?

  • Instead of echo "<script>window.location='index.php'</script>";, you tried to use header("Location: index.php");?

  • I tried, buddy, and it didn’t work.

  • We are not a forum, do not put the reply in the body of question and there is no need for the title SOLVED, much less the unnecessary use of Capslock, simply check the answer you think is correct, see the tour and understand the site first http://answall.com/tour

3 answers

2

the use of <script>window.location='index.php'</script> for redirecting is not fully recommended since simply disabling the javascript of the browser is possible to access without any problem. Instead modify the header before sending it to the browser through the php header method:

header("Location: index.php");

Try changing the verification code from:

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

for:

if (! isset($_SESSION["usuarioSenha"]) || isset($_SESSION["senha"]))
  • Thanks friend, it worked, it was worth the tip, I just adapted a little.

  • Wow, I’m glad it worked out. See you.

0

I made this file called segunrança.php, and did 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");
            }
        }
    }
?>
  • That’s an answer to your question?

  • The solution to the question

0

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

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

Ready, if the access comes typing the URL in the browser the method is GET and you will be redirecting to a blocking page, but if the user is on the authentication page, he accesses the administrative.php via POST method and the page will open normally.

  • Simply using if($_GET) already blocks any interaction through "get"

  • Truth..... (:

  • Vaaleu!!! Problem solved. thanks for the tips friends

Browser other questions tagged

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