Govind Kailas
Govind Kailas

Reputation: 2934

Passing an AD authenticated php session variable to another page

I have an AD authentication implemented in login.php, now if the auth is successful I wanted to pass the Users Given name to another php page say app.php.

login.php

    <?php
     session_start();
    if(isset($_POST['username']) && isset($_POST['password'])){
    $adServer = "ldap://ad.my_domain.com";
    $ldap = ldap_connect($adServer);
    $username = $_POST['username'];
    $password = $_POST['password'];
    $ldaprdn = 'my_server' . "\\" . $username;
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
        $bind = @ldap_bind($ldap, $ldaprdn, $password);
    if ($bind) {
    $filter="(sAMAccountName=$username)";
    $result = ldap_search($ldap,"dc=my_domain,dc=COM",$filter);
    ldap_sort($ldap,$result,"sn");
    $info = ldap_get_entries($ldap, $result);
    for ($i=0; $i<$info["count"]; $i++)
    {
        if($info['count'] > 1)
        break;
            $_SESSION['user']=$info[$i]["givenname"][0];
            #echo $_SESSION['user'];
            header("Location: app.php");        }
    @ldap_close($ldap);
    } else {
    $msg = "Invalid email address / password";
    echo $msg;
    }

}else{
?>
    <form action="#" method="POST">
    <label for="username">Username: </label><input id="username" type="text" name="username" /> 
    <label for="password">Password: </label><input id="password" type="password" name="password" />        
        <input type="submit" name="submit" value="Submit" />
    </form>
<?php } ?> 

Here is the app.php

             <?php
           session_start();session_regenerate_id();
      ?>
    <!DOCTYPE html>
    <html>
    <head>
         <title>My App ::Home Page</title>

    </head>

    <body>

    <?php
        if (!isset($_SESSION['user'])) {
        header("Location: login.php"); // If session is not set that redirect to Login Page
      }
    ?>

    // code for app 
    </body>
    </html>

AD authentication is successful but somehow the $_SESSION['user'] is not getting passed to app.php. I tried to print the value of $_SESSION['user'] in login.php which is showing the expected result. it is always getting redirected to the login.php from app.php

What am I doing wrong ? Why is isset($_SESSION['user']) failing to get the value passed from login

Upvotes: 0

Views: 1414

Answers (1)

Govind Kailas
Govind Kailas

Reputation: 2934

I had a couple of troubles but the main reason it was failing because it could not start the session. This was caused by the Whitespace before <?php and after ?> in app.php It took a while for me to figure out this silly but serious thing . Here is a good explanation

Hope this helps someone.

Upvotes: 0

Related Questions