Problems with session_start()

Asked

Viewed 2,044 times

0

I’m having trouble with my PHP code for the User Login. This code is working on local machine, however I went up in my instance Amazon and the moment I log in the server does not authenticate the session. The page login.php is in a login.xxxx.com.br subdomain and the restricted page is in another subdomain strict paginar.xxxx.com.br, so when I go to debug the code and call the login page variables in the restricted area apache informs that the variable has not been set or is apache on my server can not open a session www domains different, as I performed 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;   
}
?>
  • In your login.php the second session_start(); is too much and should be removed. On your restricted page, you lack the session_start(); at file start so you can use the session variable $_SESSION["usuario"].

  • Ivan, I reversed his last edition, as it seemed to be based on William’s reply. This ended up changing the question, and invalidating at least one of the existing answers. To clarify questions about each answer, use the comments below them, or chat. But none of the current answers solve your problem?

  • @bfavaretto None of the answers solved my problem.

3 answers

2

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

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

To solve, since the cookie must be restricted to one domain, you have two options:

1. Changing the . HTACCESS:

php_value session.cookie_domain .xxxxxx.com.br

2. Changing PHP.INI:

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

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

// Edit:

Other solution:

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 must have the same Session.save_path:

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

// Observing:

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

  • Great answer, that seems to be it +1

  • @inkeliz what argument do I use in Session.cookie_domain? I put "" in PHP.INI and it didn’t work. I am debugging with <pre> print_r($_SESSION); </pre> And still clean I have not received any data.

  • @Ivanfloripa when you modify PHP.INI you must restart the server (in the case of Apache).

  • @Guilhermenascimento of course the Web server (Apache) has been restarted.

  • @Ivanfloripa You don’t need rudeness, such a situation was not as obvious as you imagine and I was just trying to help you.

  • Try with: "ini_set('Session.cookie_domain', '.xxxxxx.com.br' );", there should be a point before the domain and then the domain of the site. Also, do what Renato Tavares said above. Download the app in Chrome: Editthiscookie, so you can find out whether or not the session cookie is on all pages.

  • @Inkeliz I used Editthiscookie and the code opens the session cookie, I also started with <?php session_start(); the restricted page code however does not appear open on the page.

  • @Guilhermenascimento I set to save in a folder the session. Very strange

  • @Guilhermenascimento opa would help a lot :)

  • //Condition for requesting the creation of the session $_SESSION["user"] = $usuario; $url = 'http://user.xxx.com.br/createsession.php'; $data = array('username' => $_POST['user']); $postString = http_build_query($data, '', '&');&#xA;&#xA; $ch = curl_init(); &#xA; curl_setopt ($ch, CURLOPT_URL, $url); &#xA; curl_setopt ($ch, CURLOPT_POST, count($data)); &#xA; curl_setopt ($ch, CURLOPT_POSTFIELDS, $postString); &#xA; curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); $post = curl_exec ($ch); The formatting here is horrible.

  • But the Session cookie data would be returned to Curl and not to the client’s browser. The session would be created, but it would not return. It should then be done to take the 'Set-Cookie' from the 'Response headers' and then create a 'setcookie' for the customer. But I think you have another solution, better, I’ll edit.

  • @Inkeliz Not the code he posted refers to the suggestion made by me in my answer the question, the code works, his problem is with another file currently.

Show 7 more comments

1

Try to use the 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 check if there are values in it.

1

To use multi-domain session you need to share the session and the cookie, the session file is in a flame folder 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 another’s session (it would be a security breach).

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>, would look something like:

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

Session.php is the one who would share the data, but this can be a bit complex to do if you have little knowledge about work 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 the user.xxxxxx.com.br, would look something like (preferably use pole to minimize invasion attempts):

Create a file called createsession.php in the realm 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 must create a request for the 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 totally safe, but you can create a TOKEN to prevent attempts to "HACK" users' accounts.

  • Guilherme I could not compile the session gave a variable compilation error not defined $post in the strict.php page

  • Undefined variable: post in /var/www/conaprom/user/index.php on line 8

  • I do not have the knowledge of the contents of this file, apparently it is not a flaw in my code but in something else totally isolated. You could put in his entire code?

  • I will post a new reply William!

  • in the answer to my question, the answer by comment the space is reduced.

  • @Ivanfloripa I like Stackoverflow precisely to avoid discussions, Stackoverflow is a question and answer system (AKA Q&A) is different from forum systems, so please edit your question and add the requested code in my previous comment. I am waiting.

  • Because this code is too extensive to answer in this area I posted in another area my implementation of your code. @Guilherme-nascimento

  • @Ivanfloripa Post then the contents of the file /var/www/conaprom/user/index.php up to line 15

Show 4 more comments

Browser other questions tagged

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