0
I did an optimization in the login and as I had problems with directory I decided to search the web and found a nice PHP resource that is the autoload. I did all the implementation according to the examples I got but I’m having problems.
Follow as my code is:
It all starts with index.php
, that is at the root of the project.
index php.
<?php
// Adicionando o arquivo de autoload, que faz o carregamento dos diretórios de forma dinâmica.
require_once( "autoload.php" );
// Verificando se existe a sessão.
session_start();
// A sessão ainda não existe. Primeiro acesso do usuário.
if ( !isset( $_SESSION[ 'logado' ] ) ) {
header( 'location:login.php' );
}
// A sessão do usuário já existe. Vericando se ainda está logado.
elseif ( $_SESSION[ 'logado' ] == false) {
header( 'location:login.php' );
}
// Usuário já conectado. Envia direto para a página inicial.
else {
header( 'location:inicio.php' );
}
?>
The first task of PHP is to add the autoload.php
, which is also at the root of the project. Follow it below:
autoload.php
<?php
// Função que carrega as classes da pasta "database".
function carregar_classes_database( $class ) {
if ( file_exists( "database/" . strtolower( $class ) . ".class.php" ) ) {
require_once( "database/" . strtolower( $class ) . ".class.php" );
}
}
spl_autoload_register( "carregar_classes_database" );
$obj1 = new Database();
// Função que carrega as classes da pasta "entity".
function carregar_classes_usuario( $class ) {
if ( file_exists( "entity/usuario/" . strtolower( $class ) . ".class.php" ) ) {
require_once( "entity/usuario/" . strtolower( $class ) . ".class.php" );
}
}
spl_autoload_register( "carregar_classes_usuario" );
$obj2 = new Usuario();
?>
I already put a echo
within the if
of file_exists
only to ensure that the file is actually valid and is.
My directory structure is in the following format:
As my session does not exist at first access to the site, I am forwarded to the login. At this time the autoload.php
has already been added.
I arrive at the login screen, where I have the input user and the input password and also the button Submit.
To action
of form
calls a login validation function, which I called validarLogin.php
validarLogin.php
<?php
// Adicionando recursos. COMENTADO PARA UTILIZAR O AUTOLOAD E EVITAR INCLUIR OS ARQUIVOS "NA MÃO".
//require_once( "database/database.class.php" );
//require_once( "entity/usuario/usuario.class.php" );
session_start();
$database = new Database();
$database->connect();
// Conexão bem sucedida.
if ( $database->getConnected() ) {
$user = new Usuario();
$user->setUsuario( $_POST[ 'usuario' ] );
$user->setSenha( $_POST[ 'senha' ] );
// Validando se o usuário e a senha são válidos.
if ( $user->exists( true, '' ) ) {
$_SESSION[ 'erro' ] = '';
$_SESSION[ 'logado' ] = true;
$_SESSION[ 'usuario' ] = $user->getUsuario();
$_SESSION[ 'nome' ] = $user->getNome() . ' ' . $user->getSobrenome();
header('location:inicio.php');
// Se o usuário for inválido volta para a tela de login.
} else {
$_SESSION[ 'erro' ] = $user->getMSG_INVALID_USER();
$_SESSION[ 'logado' ] = false;
$_SESSION[ 'usuario' ] = '';
$_SESSION[ 'nome' ] = '';
header('location:login.php');
}
}
// Ocorreu um erro na conexão. Volta para a página de login.
else {
$_SESSION[ 'erro' ] = $database->getMsgError();
$_SESSION[ 'logado' ] = false;
$_SESSION[ 'usuario' ] = '';
$_SESSION[ 'nome' ] = '';
header('location:login.php');
}
?>
I commented on the require_once
, 'cause in my head, if I’m already using the autoload
, I no longer need the required_once
.
When I submit the form login and the function above is called I have an error on the line:
$database = new Database();
Fatal error: Class 'Database' not found in /home/Ubuntu/Workspace/validarLogin.php on line 10 Call Stack: 0.4673 238080 1. {main}() /home/Ubuntu/Workspace/validarLogin.php:0
Why am I having this mistake if mine autoload has already been initiated?
PHP should not know who the class is Database
, once she is already in memory?
But the function of autoload will only exist if you upload the file
autoload.php
. In this case, invalidarLogin.php
you will need to do therequire_once("autoload.php")
also.– Woss
Thanks for the feedback, Anderson. Really, when I put the call to autoload.php in validarLogin.php it worked. But this is still a problem for me because I need to call autoload in all the files. php, which wouldn’t be much different than calling require_once. I decided to study Laravel to use it in development and avoid these kinds of problems. Even so, I appreciate your willingness to help.
– Davi'd Ferreira