gpt4 book ai didi

PHP ldap_add 函数转义 DN 语法中的 ldap 特殊字符

转载 作者:行者123 更新时间:2023-12-03 00:32:56 25 4
gpt4 key购买 nike

我正在尝试将一些用户添加到我的 Ldap DB,但是当我使用一些特殊字符(例如“,.”)时,我收到一些错误(无效的 dn 语法)。我需要一个转义所有字符的函数。我尝试了 preg_quote 但在某些情况下会出现一些错误。

提前致谢

代码:

$user = 'Test , Name S.L';

if(!(ldap_add($ds, "cn=" . $user . ",".LDAP_DN_BASE, $info))) {

include 'error_new_account.php';

}

最佳答案

编辑 2013 年 1 月:添加了对 DN 字符串中转义前导/尾随空格的支持,根据 RFC 4514 。感谢Eugenio指出这个问题。

编辑2014:I added this function to PHP 5.6 。下面的代码现在是早期 PHP 版本的类似替代品。

if (!function_exists('ldap_escape')) {
define('LDAP_ESCAPE_FILTER', 0x01);
define('LDAP_ESCAPE_DN', 0x02);

/**
* @param string $subject The subject string
* @param string $ignore Set of characters to leave untouched
* @param int $flags Any combination of LDAP_ESCAPE_* flags to indicate the
* set(s) of characters to escape.
* @return string
*/
function ldap_escape($subject, $ignore = '', $flags = 0)
{
static $charMaps = array(
LDAP_ESCAPE_FILTER => array('\\', '*', '(', ')', "\x00"),
LDAP_ESCAPE_DN => array('\\', ',', '=', '+', '<', '>', ';', '"', '#'),
);

// Pre-process the char maps on first call
if (!isset($charMaps[0])) {
$charMaps[0] = array();
for ($i = 0; $i < 256; $i++) {
$charMaps[0][chr($i)] = sprintf('\\%02x', $i);;
}

for ($i = 0, $l = count($charMaps[LDAP_ESCAPE_FILTER]); $i < $l; $i++) {
$chr = $charMaps[LDAP_ESCAPE_FILTER][$i];
unset($charMaps[LDAP_ESCAPE_FILTER][$i]);
$charMaps[LDAP_ESCAPE_FILTER][$chr] = $charMaps[0][$chr];
}

for ($i = 0, $l = count($charMaps[LDAP_ESCAPE_DN]); $i < $l; $i++) {
$chr = $charMaps[LDAP_ESCAPE_DN][$i];
unset($charMaps[LDAP_ESCAPE_DN][$i]);
$charMaps[LDAP_ESCAPE_DN][$chr] = $charMaps[0][$chr];
}
}

// Create the base char map to escape
$flags = (int)$flags;
$charMap = array();
if ($flags & LDAP_ESCAPE_FILTER) {
$charMap += $charMaps[LDAP_ESCAPE_FILTER];
}
if ($flags & LDAP_ESCAPE_DN) {
$charMap += $charMaps[LDAP_ESCAPE_DN];
}
if (!$charMap) {
$charMap = $charMaps[0];
}

// Remove any chars to ignore from the list
$ignore = (string)$ignore;
for ($i = 0, $l = strlen($ignore); $i < $l; $i++) {
unset($charMap[$ignore[$i]]);
}

// Do the main replacement
$result = strtr($subject, $charMap);

// Encode leading/trailing spaces if LDAP_ESCAPE_DN is passed
if ($flags & LDAP_ESCAPE_DN) {
if ($result[0] === ' ') {
$result = '\\20' . substr($result, 1);
}
if ($result[strlen($result) - 1] === ' ') {
$result = substr($result, 0, -1) . '\\20';
}
}

return $result;
}
}

所以你会这样做:

$user = 'Test , Name S.L';
$cn = ldap_escape($user, '', LDAP_ESCAPE_DN);
if (!ldap_add($ds, "cn={$cn}," . LDAP_DN_BASE, $info)) {
include 'error_new_account.php';
}

关于PHP ldap_add 函数转义 DN 语法中的 ldap 特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8560874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com