Using PHP and LDAP to Authenticate Against BYU's Servers

Been working on a BYU project at the law school where I only want to let BYU students post on a message board.  I needed an authentication solution and decided to give LDAP a try since I've heard it's relatively simple.  Here's the two step process: 1) Create a form that accepts a username and password as follows.

<form action=login.php method=post name=Auth>

Please log in using your NetID and password:<p>

<table cellspacing=3 cellpadding=3> <tr> <td>Username: </td> <td><input type=text name=username size=16 maxlength=15></td> </tr> <tr> <td>Password: </td> <td><input type=password name=password size=16 maxlength=15></td> </tr> <tr> <td colspan=2><input type=submit value=Authenticate style='width:100'></td> </tr> </table> </form>

 2) Create a login.php file.  This file accepts the username and password from the form, then connects to BYU's LDAP server (ldap:// - port 389).  After connecting, it binds the connection using the username (NetID) and if successful returns true.  Below, the authenticate function is called and if successful sets the 'loggedin' session variable to 'true' (not a boolean).  It then redirects back to the previous page, which, in this example is the message board I'm working on.

<head> <?php session_start(); ?> </head>


echo "test"; echo "</br>";

// get username and password from form $username = $_POST['username']; $password = $_POST['password'];

/* * checks the credentials against the LDAP server * $user - RouteY * $pass - password */ function authenticate($user,$pass){

echo "</br>"; echo "Authenticating..." . $user;

// prevents guest account access if($pass == ""){ return false; }


$Yldap_location = "ldap://"; $ldap_port = 389;

// call the ldap connect function $Ydatabase = ldap_connect($Yldap_location, $ldap_port);

// bind the connection $good = @ldap_bind($Ydatabase, "uid=".$user.",ou=People,", $pass);

if($good){ // valid credentials return true; } else{ // invalid credentials return false; }

} catch(Exception $e){ return false; } }

// call authenticate function if(authenticate($username,$password)){

// authenticate successful echo "</br>"; echo "SUCCESS";

// set session $_SESSION['loggedin'] = 'true';

// redirect echo $_SESSION['loggedin']; $url = ""; //$url = ""; header("Location: ".$url); } else{

// authenticate fails echo "</br>"; echo "FAIL";

// redirect to login header("Location:"); } ?>