Skip to content

Instantly share code, notes, and snippets.

@egulhan
Created March 25, 2014 08:48
Show Gist options
  • Save egulhan/9757542 to your computer and use it in GitHub Desktop.
Save egulhan/9757542 to your computer and use it in GitHub Desktop.
ldap_escape() function
/**
* function ldap_escape
* @source http://stackoverflow.com/questions/8560874/php-ldap-add-function-to-escape-ldap-special-characters-in-dn-syntax#answer-8561604
* @author Chris Wright
* @version 2.0
* @param string $subject The subject string
* @param bool $dn Treat subject as a DN if TRUE
* @param string|array $ignore Set of characters to leave untouched
* @return string The escaped string
*/
public static function ldap_escape($subject, $dn = FALSE, $ignore = NULL)
{
// The base array of characters to escape
// Flip to keys for easy use of unset()
$search = array_flip($dn ? array('\\', ',', '=', '+', '<', '>', ';', '"', '#') : array('\\', '*', '(', ')', "\x00"));
// Process characters to ignore
if (is_array($ignore)) {
$ignore = array_values($ignore);
}
for ($char = 0; isset($ignore[$char]); $char++) {
unset($search[$ignore[$char]]);
}
// Flip $search back to values and build $replace array
$search = array_keys($search);
$replace = array();
foreach ($search as $char) {
$replace[] = sprintf('\\%02x', ord($char));
}
// Do the main replacement
$result = str_replace($search, $replace, $subject);
// Encode leading/trailing spaces in DN values
if ($dn) {
if ($result[0] == ' ') {
$result = '\\20'.substr($result, 1);
}
if ($result[strlen($result) - 1] == ' ') {
$result = substr($result, 0, -1).'\\20';
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment