ParagonIE\Halite\Util::safeSubstr PHP Method

safeSubstr() public static method

Safe substring
public static safeSubstr ( string $str, integer $start, integer $length = null ) : string
$str string
$start integer
$length integer
return string
    public static function safeSubstr(string $str, int $start = 0, $length = null) : string
    {
        static $exists = null;
        if ($exists === null) {
            $exists = \is_callable('\\mb_substr');
        }
        if ($exists) {
            // mb_substr($str, 0, NULL, '8bit') returns an empty string on PHP
            // 5.3, so we have to find the length ourselves.
            if ($length === null) {
                if ($start >= 0) {
                    $length = self::safeStrlen($str) - $start;
                } else {
                    $length = -$start;
                }
            } elseif (!\is_int($length)) {
                throw new InvalidType('Argument 3: integer expected');
            }
            // $length calculation above might result in a 0-length string
            if ($length === 0 || $start > self::safeStrlen($str)) {
                return '';
            }
            return \mb_substr($str, $start, $length, '8bit');
        }
        if ($length === 0) {
            return '';
        }
        // Unlike mb_substr(), substr() doesn't accept NULL for length
        if ($length !== null) {
            return \substr($str, $start, $length);
        } else {
            return \substr($str, $start);
        }
    }

Usage Example

Beispiel #1
0
 /**
  * Get the configuration for this version of halite
  *
  * @param string $stored   A stored password hash
  * @return SymmetricConfig
  * @throws InvalidMessage
  */
 protected static function getConfig(string $stored) : SymmetricConfig
 {
     $length = Util::safeStrlen($stored);
     // This doesn't even have a header.
     if ($length < 8) {
         throw new InvalidMessage('Encrypted password hash is way too short.');
     }
     if (\hash_equals(Util::safeSubstr($stored, 0, 5), Halite::VERSION_PREFIX)) {
         return SymmetricConfig::getConfig(Base64UrlSafe::decode($stored), 'encrypt');
     }
     $v = \Sodium\hex2bin(Util::safeSubstr($stored, 0, 8));
     return SymmetricConfig::getConfig($v, 'encrypt');
 }
All Usage Examples Of ParagonIE\Halite\Util::safeSubstr