Block pages using login and Session

Asked

Viewed 6,839 times

0

I’m developing a website that has an administrative panel. That panel has a login, my problem is that I can enter the panel through the link, that is to say, it is not safe, anyone is able to enter if they know the name of the files. Example:

http://localhost/om/admin/Painel.php

If I do this enter me on the site and I can accomplish everything without being administrator, to fix this I know that can be done with Session, but I don’t know how to.

I don’t have any code, I just have a file called _config.php that is being called in all files in the panel.

  • Before creating a question give a searched in Stackoverflow because it already has several answers to this problem, see my answer for example: http://answall.com/questions/70758/acesvia-url/70765#70765

4 answers

2

This problem is very common and it is up to you to define who can access the page or not. The @Carlos example illustrates how to solve the problem.

The logic behind this is: All users have access to all pages of your application, so you must set a level of access to each. In this example above the suggestion was to test if the user has already logged in previously and allow access. If you have not logged in it gives an error message. Many web-sites redirect the user to the login screen again if the user does not have permission.

I recommend reading the function header php. With this function you can redirect the user to another page.

Important remarks:

  1. Remember that when using session you should always call the function session_start() before working with the super global variable $_SESSION;
  2. When using the function header to redirect a user you must take care not to send any output (output) to the browser, be it a space, a enter, or any HTML tag.

2

In the file that checks user information, store the user ID in a session.

<?php
session_start(); // Inicia a sessão

// Pega os dados do usuário
$stmt = $con->prepare("SELECT usuarioId FROM usuarios WHERE login = ? AND senha = ?");
$stmt->bind_param('ss', $login, $senha);
$stmt->execute()
$res = $stmt->get_result();

// Verifica se encontrou o usuário
if ($res->num_rows){
    $row = $res->fetch_array(MYSQLI_ASSOC);
    $_SESSION['user'] = $row['usuarioId']; // Marca a global para verificar se o usuário está logado.
    header('Location: http://localhost/sitema/inicio.php'); // Página do sistema
    exit; // Encerra a execução do script
} else {
   // Se não encontrou o usuário, manda de volta para o form de login
   header('Location: http://localhost/sitema/login.php'); // Página do sistema
   exit; // Encerra a execução do script
}

Create the file: restrito.php

<?php
session_start();
// Se o usuário não está logado, manda para página de login.
if (!isset($_SESSION['user'])) header("Location: http://localhost/sistema/login.php");
exit; // Encerra a execução do script

Include the file at the beginning of all pages you want to block for those who are not logged in.

Heed: The archive restrito.php should be the first expression of your page before anything else. Example:

<?php require_once('caminho/para/restrito.php');?><DOCTYPE html>...

You can’t even have one (space) blank before.

  • gives all the only problem is that when logging in with the right data appears in the same message that I am not allowed

  • Is your query to the bank bringing the right data? If so, you have logged there in the variables $_SESSION after the query the user is logged in? Post your code here to see what’s going wrong, the query file, the restriction file and a page file. So we can take a closer look at the problem.

  • The code I have is the one above, the problem is that the column to log in should not be prepared for arrays, can not do otherwise simpler than the one above, that array

  • I made it a little easier in the code there, so if you’re still struggling, let us know. The way to do it is using Session itself, could use Cookies but I believe it is more complicated, and not necessary. The variable $_SESSION, is nothing more than a array global, for the use of them you always have to declare the session_start() at the beginning of the code, it always has to be the first thing (with rare exceptions).

  • This says I have a redirect cycle

  • checks if the file restrito.php is being included on the login page, in case the page that has the login form. There cannot be restricted, otherwise the user will never be able to enter the system.

  • is how I have 2 files( one that has the login form) and another file that has the login connection to the database the checks and everything, where I have to put this : <?php session_start(); $result = mysql_query("SELECT usuarioId FROM usuarios WHERE login = {login} AND password = {$password}"); if (Count($result)>0){ $_SESSION['user'] = $result[0]['usuarioId']; } is in this login file that you are doing the checks ... in the right database?

  • That’s right, and if you don’t find the user you redirect to the form again. If you find it redirects to the system page.

  • I updated the code there, with some details that were missing, I also commented on it to you better understand the process, see if it helps.

Show 4 more comments

1

I took the liberty of creating this class start that goes against the nominee.

this way in the future will be included all the logic necessary for your project adding a method to class.

Is a start....

class Auth {

    public static function handleLogin(){
        session_start();
        if (!isset($_SESSION['user_logged_in'])) {

            header('location: ' . URL);
            exit();
        }
    }
}

At the beginning of each page just put...

Auth::handleLogin

To be able to work you have to start URL variable for example...

define('URL', 'http://localhost/');

And once credentials are validated you must :

$_SESSION['user_logged_in']=true;
  • I’d like to speak to you in person, it would be possible?

  • Ask your question... I’m happy to help! If you like the answer don’t forget to vote... That’s how this community works.

  • I’m new to this, and all these answers have left me confused

  • Opa, @cloud, chambelix response is good, you can use instead of file restrito.php. Although for someone who’s starting out, it can be a little confusing. I am doing a "mini course" on object-oriented programming, creating just an administration panel, if you want to follow the blog Devcia

  • All right...by chat room?

  • Let it be, I don’t want to bother you, this anyway has to go, you’ve already helped me a lot I’m going to see for myself and testing what’s wrong and what’s right, thanks guys

  • All right... By the way if you want to do a specific validation say... I would also recommend creating a class to handle Session... If you’re starting to read and understand the php classes it will be very useful.

  • the problem is then apply on the site ... but slowly goes away ^^

  • For what I presented when applying in production the URL has to be Domain... In other words, replace the localhost with the domain. However to put into production a much better version should happen.

Show 4 more comments

0

When you log in, you play the information on a Session then on all pages check if there is a Session before displaying the page otherwise redirects to the login.

Note: In case it has not been clear let me know which complement.

  • That’s how I don’t understand much of Session login works will bd check the values .... what I want is not to enter the panel through the link :

Browser other questions tagged

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