I'm trying to add some users to my Ldap DB but I get some errors (invalid dn syntax) when I use some special characters like ",.". I need a function that escape all characters. I try preg_quote but I get some errors in some cases.
Thanks in advance
Code:
$user = 'Test , Name S.L';
if(!(ldap_add($ds, "cn=" . $user . ",".LDAP_DN_BASE, $info))) {
include 'error_new_account.php';
}
Just a heads up if your not on PHP 5.6 yet, you can mirror the exact PHP 5.6 function
ldap_escape()
using the methods I created below, keep in mind this is meant for use in a class. The above answer doesn't perform exactly like theldap_escape
function, as in it doesn't escape all characters into a hex string if no flags have been given, so this would be more suitable for a drop in replacement for earlier versions of PHP, in an object oriented way.I've documented every line for an easier understanding on whats going on. Scroll down for output.
Methods (Compatible with PHP 5 or greater):
Tests (be aware that LDAP_ESCAPE constants are only available in PHP 5.6):
Github Gist link: https://gist.github.com/stevebauman/0db9b5daa414d60fc266
EDIT Jan 2013: added support for escaping leading/trailing spaces in DN strings, per RFC 4514. Thanks to Eugenio for pointing out this issue.
EDIT 2014: I added this function to PHP 5.6. The code below is now a like-for-like drop-in replacement for earlier PHP versions.
So you would do:
PHP 5.6 Beta released
ldap_escape()
function recently and it is in effect, However, this version is not production ready at present, you can very use it for your development purposes as of now.Those characters must escaped to be part of the data of a distinguished name or relative distinguished name. Escape the character (as in all LDAP) with a backslash 2 hex digit, such as
\2a
. Anything else would not be in compliance with the standards body documents. See RFC4514 for more specific information regarding the string representation of distinguished names.