Home > database >  How to determine whether PHP password_hash functions supports a 'thread' option?
How to determine whether PHP password_hash functions supports a 'thread' option?

Time:09-26

For the PHP function password_hash the manual says that passing the number of threads is "Only available when PHP uses libargon2, not with libsodium implementation.".

An error will be given if the thread option is set when it's not available.

For library code, how can I determine at run-time whether the thread option is available?

CodePudding user response:

The PASSWORD_ARGON2_DEFAULT_THREADS constant is only defined when libargon2 is used:

PASSWORD_ARGON2_DEFAULT_THREADS Default number of threads that Argon2lib will use. Not available with libsodium implementation.

So you can just test if the constant exists:

if(defined('PASSWORD_ARGON2_DEFAULT_THREADS'))
{
   // Set the number of threads
   ...
}

CodePudding user response:

Check if the extension is loaded and remove the option if not.

function hash_password(
    string $password,
    string | int | null $algo,
    array $options = []
): string {
    if (!extension_loaded('libargon2') && isset($options['threads'])) {
        unset($options['threads']);
    }

    return password_hash($password, $algo, $options);
}
  •  Tags:  
  • php
  • Related