On Tue, Nov 3, 2015 at 11:13 PM, Côme Chilliet <c...@opensides.be> wrote:

> I got mail from someone saying that in previous version, calling
> ldap_connect($host, NULL) would use default port.
> While now it is considered as trying to use port 0 and trigger an error.
>

I believe the current behavior (interpret as zero and trigger error) is
correct.



> I’m a bit troubled about it because the documentation says:
>  resource ldap_connect ([ string $hostname = NULL [, int $port = 389 ]] )
> So $port defaults to 389 and not to NULL, and it says nothing about
> accepting NULL as second parameter.
>

Let's compare to another PHP function that takes a numeric optional
parameter with a non-zero default:

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Note that SORT_STRING === 2, SORT_REGULAR === 0.

If you pass null for the second argument, you get the SORT_REGULAR
behavior, not the default SORT_STRING behavior:

print_r(array_unique([ 1, '1', '1a' ], null));


That said, it does seem handful to be able to pass NULL to ask for default
> port without remembering which one it is.
> The context is something like:
> $port = NULL;
> if (isset($options['port'])) {
>         $port = $options['port'];
> }
> $resource = ldap_connect($host, $port);
>

A few reasons I'd offer as arguments against this.  $port is deprecated, so
why add features to deprecated arguments?  Other PHP internal functions
don't behave this way (array_unique, socket_create_listen, ssh2_connect,
etc.), so why go against the grain?  Why not document (in a comment) the
preferred way of doing this, which might be:

if (isset($options['port']))
    $resource = ldap_connect($host, $options['port']);
else
    $resource = ldap_connect($host);



> Right now it either needs an if statement or hardcoding 389 instead of
> NULL as the default. In the C code we use the constant LDAP_PORT for this
> but there is no such thing in PHP.
> Any ideas/comments about this?
>

A PHP user-land constant like LDAP_DEFAULT_PORT might help users out
marginally, but to my knowledge no other port numbers are exposed as such
in PHP.  Like ssh2_connect, for example, uses a raw 22.

If one wanted truly robust (paranoid) code, you'd probably want to do:

$port = getservbyname('ldap', 'tcp');

if (isset($options['port']) && is_numeric($options['port']))
    $port = intval($options['port']);

$resource = ldap_connect($host, $port);

And this could go in a comment and solve the whole issue without code
changes.

Reply via email to