Skip to content

Instantly share code, notes, and snippets.

@DrizzlyOwl
Created September 28, 2021 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrizzlyOwl/0ef52179b07189785ec47765792e40c8 to your computer and use it in GitHub Desktop.
Save DrizzlyOwl/0ef52179b07189785ec47765792e40c8 to your computer and use it in GitHub Desktop.
Query LDAP using PHP
<?php
$sam = 'user.name';
$username = $sam . "@mydomain.co.uk";
$password = "foobar";
$port = 636;
$host = "111.222.333.444";
$ldaphost = "ldaps://$host:$port";
$ldap_base_dn = 'DC=MyDomain,DC=co,DC=uk';
$ldapUsername = "cn=" .$username . "," . $ldap_base_dn;
$ldapPassword = $password;
// Uncomment below line for more debugging output
// ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
$ds = ldap_connect($ldaphost) or die("Could not connect to LDAP server");
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
// now we need to bind to the ldap server
$ldapbind = ldap_bind($ds, $username, $password);
if ($ldapbind) {
// Write a suitable LDAP query here...
$search_filter = '(CN=*)';
// Specify an array of AD User object attributes to return
$attributes = array('*');
// Run the query
$result = ldap_search($ds, $ldap_base_dn, $search_filter, $attributes, 0, 0);
if (false !== $result){
// Collect the results
$entries = ldap_get_entries($ds, $result);
// Gross but easy.. print to screen
print_r($entries);
} else {
echo "No results found";
}
// Disconnect
ldap_unbind($ds);
} else {
echo "LDAP bind failed...";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment