Problems with session start () [closed]

Closed. this question is out of scope and is not currently accepting answers.

Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 5 years ago .

improve this question

I am having problem in my PHP code for the user Login. This code is working on local machine, however I climbed on my amazon instance and the moment I log in the server does not authenticate the session. The login Page.php is in a subdomain login.xxxx.com.br and the restricted page is in another subdomain paginarestrita.xxxx.com.br, so when I debug the code and call the login page variables in the restricted area apache informs that the variable has not been defined or apache on my server can not open a session of domains www different, because I performed tests with the files in 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;   
}
?>
Author: bfavaretto, 2014-12-22

3 answers

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

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

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

1. Change the .HTACCESS:

php_value session.cookie_domain .xxxxxx.com.br

2. Change the PHP.INI:

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

This way, the cookie will be saved across the domain, not restricted to a subdomain. : D

// Edit:

Other solution:

1. Change parameters of 'session_set_cookie':

$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.

 2
Author: Inkeliz, 2014-12-24 00:00:16

1st try to use session_start(); only once in login.

2nd Place session_start(); at the top 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 check if there are values in it.

 1
Author: Renato Tavares, 2014-12-23 17:58:31

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 Sessions to mix, in other words one domain cannot access the session of another (it would be a security flaw).

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

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

O session.php is 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 must send a request to user.xxxxxx.com.br, it would look something like (preferably use post to minimize intrusion attempts):

Create a file named createsession.php in the Domain user.xxxx.com.br 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 output 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 entirely secure, however you can create a TOKEN to prevent attempts to" hack "users' accounts.

 1
Author: Guilherme Nascimento, 2014-12-23 22:16:33