Problems with session_start () [closed]

0

I'm having trouble with my PHP code for User Login . This code is working on local machine, however I went up in my amazon instance and the moment I log in the user the server does not authenticate the session. The login.php page is in a subdomain login.xxxx.com.br and the restricted page is in another subdomain paginarestrita.xxxx.com.br, so when I go to debug the code and call the variables of the login page in the restricted area apache informs that the variable has not been defined, or that apache on my server can not open a different www domain session since I ran tests with the files in the same subdomain.

login:

<?php session_start(); ?>
<?php
require('db_conn.php');
if(isset($_POST['entrar'])){
    $usuario = $_POST['usuario'];
    $senha = $_REQUEST['senha'];
    $sql= ("SELECT * FROM login WHERE usuario ='$usuario' AND senha ='$senha'");
    $query=mysql_query($sql) or die (mysql_error());
    $results= mysql_num_rows($query);

    if($results == 0){
        echo "<script>alert('Erro ao logar')</script>";
        echo "<meta HTTP-EQUIV='refresh' CONTENT='5;URL=http://portal.xxxxx.com.br'>";
    }else{
        // Cria uma sessão que identifica se o usuário efetuou o login
        session_start();
        $_SESSION["usuario"]=$usuario;
        echo "<script>alert('Usuário autenticado com sucesso')</script>";
        echo "<meta HTTP-EQUIV='refresh' CONTENT='0;URL= http://user.xxxxxx.com.br'>";
    }
}
?>

Restricted Page:

<?php
$usuario=$_SESSION["usuario"];
if(isset($usuario)){
  echo "<script>alert('Usuário autenticado com sucesso')</script>";
  return true;
}else{
    //session_destroy();
    header( "Location:http://portal.xxxxx.com.br/" , TRUE , 302 );
}

// Logout
if( isset($_GET["acao"]) && $_GET["acao"]=="logout" ) {
    // Destrói todos os dados da sessão
    session_destroy();
    // Redireciona o usuário para o formulário de login
    header( "Location:http://portal.xxxxxx.com.br/" , TRUE , 302 );
    exit;   
}
?>
    
asked by anonymous 22.12.2014 / 23:23

3 answers

2

This is because of the cookie that saves the session, usually with PHPSESSION name, is restricted to only one subdomain.

Check, in an old F12 if the shipping headers on the restricted page are including cookies, with the values that are reported in the headers of the login.

To solve, since the cookie must be restricted to a subdomain, you have two options:

1. Change .HTACCESS:

php_value session.cookie_domain .xxxxxx.com.br

2. Change PHP.INI:

session.cookie_domain = ".xxxxxx.com.br"

In this way, the cookie will be saved throughout the domain, not restricted to a subdomain. : D

// Edit:

Other solutions:

1. Change 'session_set_cookie' parameters:

$configAtual = session_get_cookie_params();

    session_set_cookie_params(
        $configAtual["lifetime"],
        $configAtual["path"],
        '.xxxxxx.com.br',
        $configAtual["secure"],
        $configAtual["httponly"]
    );

    session_start();

2. Both should have the same session.save_path:

ini_set('session.save_path', '/var/lib/php/session'); // exemplo

// Note:

Try using anonymous browser or delete the cookie from the old session and choose the same folder to save the session.

    
23.12.2014 / 21:21
1

1 Try to use session_start(); only once in the login.

2nd Place session_start(); at the beginning of the restricted page file.

I think the second option is the one that will solve your problem, remember that you need to log in before trying to verify if there are values in it.

    
23.12.2014 / 18:58
1

To use session with multiple domains it is necessary to share the session and the cookie, the session file is in a folder called tmp and each domain usually has its own folder or "ID" that does not allow the sessions to mix , in other words one domain can not access the session from another (it would be a security hole).

There are several methods to share a session with multiple domains, a simple idea would be to create an isolated domain that would share the data used <script> , it would look something like:

<script src="//shared.xxxxxx.com.br/session.php"></script>

The session.php is the one who would share the data, however this can be a bit complex to do if you have little knowledge about working front-end combined with back-end

Another way would be to use PHP itself to access the future domain (in your case something like user.xxxxxx.com.br )

Before directing access, you should send a request to user.xxxxxx.com.br , it would look something like (preferably use post to minimize attempts to break in):

Create a file named createsession.php in the user.xxxx.com.br domain and add the following content:

<?php
if (isset($_POST['username'])) {
    session_start();
    $_SESSION["usuario"] = $_POST['username'];
    echo 'OK';
}

In the login file you should create a request for user.xxxxx.com.br , add this:

$url = 'http://user.xxxxx.com.br/createsession.php';
$data = array('username' => $_POST['usuario']);
$postString = http_build_query($data, '', '&');

$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL, $url); 
curl_setopt ($ch, CURLOPT_POST, count($data)); 
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postString); 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
$post = curl_exec ($ch);

The result of the file should be something like:

<?php
session_start();

require('db_conn.php');
if(isset($_POST['entrar'])){
    $usuario = $_POST['usuario'];
    $senha = $_REQUEST['senha'];
    $sql= ("SELECT * FROM login WHERE usuario ='$usuario' AND senha ='$senha'");
    $query=mysql_query($sql) or die (mysql_error());
    $results= mysql_num_rows($query);

    if($results == 0){
        echo "<script>alert('Erro ao logar')</script>";
        echo "<meta HTTP-EQUIV='refresh' CONTENT='5;URL=http://portal.xxxxx.com.br'>";
    }else{
        // Cria uma sessão que identifica se o usuário efetuou o login
        //session_start(); -- linha desnecessária
        $_SESSION["usuario"] = $usuario;

        $url = 'http://user.xxxxx.com.br/createsession.php';
        $data = array('username' => $_POST['usuario']);
        $postString = http_build_query($data, '', '&');

        $ch = curl_init(); 
        curl_setopt ($ch, CURLOPT_URL, $url); 
        curl_setopt ($ch, CURLOPT_POST, count($data)); 
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $postString); 
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
        $post = curl_exec ($ch);

        if (trim($post) === 'OK') {
            echo "<script>alert('Usuário autenticado com sucesso')</script>";
            echo "<meta HTTP-EQUIV='refresh' CONTENT='0;URL= http://user.xxxxxx.com.br'>";
        } else {
            $_SESSION["usuario"] = NULL;//Remove sessão

            echo "<script>alert('Não pode compartilhar a sessão')</script>";
            echo "<meta HTTP-EQUIV='refresh' CONTENT='5;URL=http://portal.xxxxx.com.br'>";
        }
    }
}
?>

This second method is not completely secure, but you can create a TOKEN to prevent attempts to "HACK" user accounts.

    
23.12.2014 / 23:16