Zend_Crypt_Math::randBytes PHP Method

randBytes() public static method

Return a random strings of $length bytes
public static randBytes ( integer $length, boolean $strong = false ) : string
$length integer
$strong boolean
return string
    public static function randBytes($length, $strong = false)
    {
        $length = (int) $length;
        if ($length <= 0) {
            return false;
        }
        if (function_exists('random_bytes')) {
            // available in PHP 7
            return random_bytes($length);
        }
        if (function_exists('mcrypt_create_iv')) {
            $bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
            if ($bytes !== false && strlen($bytes) === $length) {
                return $bytes;
            }
        }
        if (file_exists('/dev/urandom') && is_readable('/dev/urandom')) {
            $frandom = fopen('/dev/urandom', 'r');
            if ($frandom !== false) {
                return fread($frandom, $length);
            }
        }
        if (true === $strong) {
            require_once 'Zend/Crypt/Exception.php';
            throw new Zend_Crypt_Exception('This PHP environment doesn\'t support secure random number generation. ' . 'Please consider installing the OpenSSL and/or Mcrypt extensions');
        }
        $rand = '';
        for ($i = 0; $i < $length; $i++) {
            $rand .= chr(mt_rand(0, 255));
        }
        return $rand;
    }

Usage Example

Exemplo n.º 1
0
 /**
  * Generate CSRF token
  *
  * Generates CSRF token and stores both in {@link $_hash} and element
  * value.
  *
  * @return void
  */
 protected function _generateHash()
 {
     $this->_hash = md5(Zend_Crypt_Math::randBytes(32));
     $this->setValue($this->_hash);
 }
All Usage Examples Of Zend_Crypt_Math::randBytes