PHP$_SESSION is not recognized on the same server at a different URL

Asked

Viewed 214 times

1

I have a.php check file that checks whether the user’s session was started after logging in, which happens is the following:

There are two Urls:

https://www.site.com.br/controle/usuario/

And inside it is a link that leads to another URL:

https://www.site.com.br/b2b/usuario/

At the beginning of each page has included the code:

<?php
if( !session_id() ) {
    @session_start();
}
?>

The file verifies.php is the same for both environments, but when opening the link in a target="_BLANK", the other URL goes through the file verifies.php and the $_SESSION['user'] is not recognized and forwards the user out of the environment, but the source tab does not lose the session:

<?php
if( !isset($_SESSION['usuario']) ) {

    @session_regenerate_id(true);
    unset($_SESSION['usuario']);
    @session_destroy();
    @session_start();
    echo "<script>window.alert('Acesso não autorizado [SECTION OFF]!');</script>";
    echo "<script>parent.location.href='home/';</script>";
    exit();

}
?>

Taking into account that the call of the destination URL is made both via tag and in Jquery . ajax();

The login code follows below:

<?php
include '../../_inc/db.conn.php';

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Acesso restrito');}

$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false)
    die('Acesso restrito');

$emailuserlogin = $_POST['usuario_email'];
$emailuserlogin = strip_tags($emailuserlogin);
$emailuserlogin = addslashes($emailuserlogin);
$emailuserlogin = trim($emailuserlogin);
#
$passworduserlogin = $_POST['usuario_senha'];
$passworduserlogin = strip_tags($passworduserlogin);
$passworduserlogin = addslashes($passworduserlogin);
$passworduserlogin = trim($passworduserlogin);
$passworduserlogin = md5($passworduserlogin);

$usuarioSQL = "SELECT * FROM `usuario` WHERE `usuario_email` = '" . mysqli_real_escape_string($conn, $emailuserlogin) . "' AND `usuario_senha` = '" . mysqli_real_escape_string($conn, $passworduserlogin) . "' LIMIT 1;";

$usuarioQuery = mysqli_query($conn, $usuarioSQL) or mysqli_error($conn);

$contaUsuario = mysqli_num_rows($usuarioQuery);

if ( $contaUsuario == 1 ) {

    $usuario = mysqli_fetch_array($usuarioQuery);

    $_SESSION['usuario'] = array();

    foreach($usuario as $campo => $valor) {
        $_SESSION['usuario'][$campo] = $valor;
    }

    echo "<h5 class='alert alert-success text-black font-bold'>Logado! Redirecionando...</h5>";
    echo "<script>setTimeout('parent.location.href=\"home\"', 1400);</script>";
    exit();

}

if( $conta == 0 ) {
    echo "<h5 class='alert alert-danger text-black font-bold'><span class='text-bold'>Erro!</span> Login/Senha inválida.</h5>";
    exit();
}
?>
  • Take the @ out of front of session_start, in fact avoid suppressing almost any error. It is likely that you have some output before session_start and so it does not start, as you deleted the error is not displayed.

  • It does not have an output, I suppress it due to the production environment, which I now needed to do a maintenance, I tested a window.Alert on a Count($_SESSION['user']); but the value 0 is displayed;

1 answer

1


The session_start must come before any use of the variable $_SESSION, you’re using it wrong:

<?php
if( !isset($_SESSION['usuario']) ) {

    @session_regenerate_id(true);
    unset($_SESSION['usuario']);
    @session_destroy();
    @session_start();
    echo "<script>window.alert('Acesso não autorizado [SECTION OFF]!');</script>";
    echo "<script>parent.location.href='home/';</script>";
    exit();

}
?>

Aside from this use of arrobas to suppress the errors are confusing you all, it was probably to be displaying some errors by failures in the way you set up, problems in your script:

  • The session_start should come at the beginning
  • unset is unnecessary if isset already states that $_SESSION['usuario'] there is no
  • no need to use session_regenerate_id and session_destroy at the same time, it is the same as you change the ID of something and then delete it, it is in vain.

Just do it:

<?php
session_start();

if ( !isset($_SESSION['usuario']) ) {
    echo "<script>window.alert('Acesso não autorizado [SECTION OFF]!');</script>";
    echo "<script>parent.location.href='home/';</script>";
    exit;
}

And in the other script do this:

<?php
if( !session_id() ) {
    session_start();
}
?>

See if there is a header error.


Problems with the login code

These problems do not affect, but they are low executions:

$emailuserlogin = $_POST['admin_email'];
$emailuserlogin = strip_tags($emailuserlogin);
$emailuserlogin = addslashes($emailuserlogin);
$emailuserlogin = trim($emailuserlogin);

$passworduserlogin = $_POST['admin_senha'];
$passworduserlogin = strip_tags($passworduserlogin);
$passworduserlogin = addslashes($passworduserlogin);
$passworduserlogin = trim($passworduserlogin);
$passworduserlogin = md5($passworduserlogin);

No need to use strip_tags and addslashes if you’re already using mysqli_real_escape_string, can reduce a lot of things.

Another tip, whenever possible use include_once, only use include if it is something that can be included more than once, if it is not the case then use include_once

The problem that’s probably affecting everything is that you’re saving the value of mysqli_fetch_array and a variable, this function is not equal to fetchAll of PDO, it is similar to the use of yield, then this won’t work:

$usuario = mysqli_fetch_array($usuarioQuery);

$_SESSION['usuario'] = array();

foreach($usuario as $campo => $valor) {
    $_SESSION['usuario'][$campo] = $valor;
}

Actually as your code returns only one item, so neither need foreach or while, to simplify you could simply make use mysqli_fetch_assoc that will take only the columns and their values.

Another problem in your script is that you probably lack the session_start (unless you’ve added db.conn.php), add at the beginning session_start();

Do exactly this, don’t change anything:

<?php
session_start();

include_once '../../_inc/db.conn.php';

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Acesso restrito');}

$pos = strpos($_SERVER['HTTP_REFERER'],getenv('HTTP_HOST'));
if($pos===false)
    die('Acesso restrito');

$emailuserlogin = $_POST['admin_email'];
$emailuserlogin = trim($emailuserlogin);

$passworduserlogin = $_POST['admin_senha'];
$passworduserlogin = trim($passworduserlogin);
$passworduserlogin = md5($passworduserlogin);

$usuarioSQL = "SELECT * FROM `usuario` WHERE `usuario_email` = '" . mysqli_real_escape_string($conn, $emailuserlogin) . "' AND `usuario_senha` = '" . mysqli_real_escape_string($conn, $passworduserlogin) . "' LIMIT 1;";

$usuarioQuery = mysqli_query($conn, $usuarioSQL) or mysqli_error($conn);

$contaUsuario = mysqli_num_rows($usuarioQuery);

if ( $contaUsuario == 1 ) {

    $_SESSION['usuario'] = mysqli_fetch_assoc($usuarioQuery);

    echo "<h5 class='alert alert-success text-black font-bold'>Logado! Redirecionando...</h5>";
    echo "<script>setTimeout('parent.location.href=\"home\"', 1400);</script>";
    exit;

} else {
    echo "<h5 class='alert alert-danger text-black font-bold'><span class='text-bold'>Erro!</span> Login/Senha inválida.</h5>";
    exit;
}
?>
  • @Eliseub. I just edited the answer, read it calmly and try to understand the script.

  • Now was show, less and more practical, it was worth it, now I need to find the reason not recognize session of another directory in new tab, the more was of great value.

  • And yes, db.conn.php has in the first line the session_start(); Gratitude Guilherme.

  • @Eliseub. in the script that is not running the session do this var_dump($_SESSION); after session_start and tell me what appears.

  • array(2) { ["phpmailer"]=> array(12) { ["host"]=> string(19) "cp-cp2.XXXXXXX.net" ["smtPauth"]=> string(4) "true" ["porta"]=> string(3) "587" ["smtpSecure"]=> string(4) "true" ["smtpAutoTls"]=> string(5) "false" ["username"]=> string(27) "[email protected]" ["password"]=> string(22) "XXXXXXXXXX" ["emailSender"]=> string(27) "[email protected]" ["emailFrom"]=> string(27) "[email protected]" ["fromName"]=> string(9) "CROSSLIFE" ["comCopy"]=> string(34) "[email protected]" ["charset"]=> string(5) "utf-8" } ------ Prints defined session values, but not login values.

  • On the source page var_dump() prints the user’s session, but on the destination page shows nothing.

  • Solved, in htaccess treating permalink, thank you!

  • @Eliseub. so the problem was the domain that this different, kind with one www and other without?

Show 3 more comments

Browser other questions tagged

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