<?php
// basic sequence with LDAP is connect, bind, set pagedResults control,
// search, interpret search result, re-set pagedResults control as required,
// close connection

echo "<h3>LDAP pagedResults query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("ldap://:9011");  // must be a valid LDAP server!
echo "connect result is [" . $ds . "]<br />";

if ($ds) {
	if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
		echo "Using LDAPv3<br />";
	} else {
		echo "Failed to set protocol version to 3<br />";
	}

	echo "Binding ...";
	$r = ldap_bind($ds);    // this is an "anonymous" bind, typically
                                // read-only access
	echo "Bind result is [" . $r . "]<br />";

	//if (ldap_set_option($ds, LDAP_OPT_SIZELIMIT, 4)) {
	//	echo "setting sizelimit<br />";
	//} else {
	//	echo "Failed to set sizelimit<br />";
	//}

	$pageSize = 3;
	$pageCookie = "";

	while (1) {
		echo "Setting pagedResults control... ";
		ldap_ctrl_paged_results($ds, $pageSize, 1, $pageCookie);

		$base = "dc=example,dc=com";
		$filter = "(sn=*)";
		echo "Searching for \"" . $filter . "\" in \"" . $base . "\"...";
		// Search surname entry
		$sr=ldap_search($ds, $base, $filter); 
		echo "Search result is [" . $sr . "]<br />";

		echo "Number of entires returned is " . ldap_count_entries($ds, $sr) . "<br />";

		echo "Getting entries ...<p>";
		$info = ldap_get_entries($ds, $sr);
		echo "Data for " . $info["count"] . " items returned:<p>";

		for ($i=0; $i<$info["count"]; $i++) {
			echo "dn is: " . $info[$i]["dn"] . "<br />";
			echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
			echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
		}

		ldap_ctrl_paged_results_resp($ds, $sr, $pageCookie);
		if ($pageCookie == "") {
			break;
		}

		echo "<br /><hr /><hr />";
	}

	echo "Closing connection...<br />";
	ldap_close($ds);

} else {
	echo "<h4>Unable to connect to LDAP server</h4>";
}
?> 
