Reading a cookie (or env variable) for a php-ldap search

Wrote a little script in php that takes an environment variable (or cookie) value and uses it to do an LDAP search. Result goes to STDOUT where they can read it using the same javascript they executed it with.

Just the code right now, will annotate with explainations later.

<?php
// Experimentally set a cookie like what your web devs create
// User ID value is first component of pipe delimited cookie value
// setcookie("useridentitycookie","G001001~|~PHILIP~|~LEMBO",
time()+3600,"/","example.com");
	
// Print the cookie value to STDOUT to validate
// echo $_COOKIE['useridentitycookie'];
// Grab the cookie value and arrayify it (split on "|")
$pieces = explode('|', $_COOKIE['useridentitycookie']);
// Assign first value to user identity variable
$sm_user = $pieces[0];
// Trim extraneous tilde ("~") characters
$sm_user = ereg_replace("~", "", $sm_user);
	
// If getting user identiy from Siteminder header variable do this
// instead (a lot less work, but not nearly as much fun)
// $sm_user=$_SERVER['HTTP_SM_USER'];
	
// Define some basic variables for LDAP search
$dirHost = "ldap.example.com";
$usrbase = "dc=example,dc=com";
// Save CPU cycles on the server by restricting the attrs returned
$attrs = array("cn","street","l","st","c","postalcode");
	
// Here are your default values, in case the identity can't be found
$dstreet = "1600 Pennsylvania Avenue ";
$dl = "Washington";
$dst = "DC";
$dc = "US";
$dpostalcode = "20500";
	
// If the identity value is there, do an LDAP search using it
if($sm_user) {
	
	$query = "(uid=$sm_user)";
	$ds = ldap_connect($dirHost);
	$r = ldap_bind($ds);
	$sr = ldap_search($ds, $usrbase, $query, $attrs);
	$info = ldap_get_entries($ds, $sr);
	for($i=0; $i<$info["count"]; $i++) {
                // To accomodate multivalued attributes, php-ldap treats all
                // attribute values as an array, so you need to use index
		$dn = $info[$i]["dn"][0];
		$cn = $info[$i]["cn"][0];
		$street = $info[$i]["street"][0];
		$l = $info[$i]["l"][0];
		$st = $info[$i]["st"][0];
		$c = $info[$i]["c"][0];
		$postalcode = $info[$i]["postalcode"][0];
                // Zip + 4 gives us heartburn
		$postalcode = substr($postalcode, 0, 5);
                // In my case we just printed the results to STDOUT,
                // delimited by pipe ("|") characters
		echo "$cn|$l|$st|$c|$postalcode";
	
	}
        // Be polite, close your LDAP connection gracefully
	ldap_close($ds);
}
	
else {
        // Print the defaults if no identity value is found
	echo "NOT LOGGED IN|$dl|$dst|$dc|$dpostalcode";
}
	
?>