PHP 8.1.20 Released!

random_bytes

(PHP 7, PHP 8)

random_bytesGet cryptographically secure random bytes

Açıklama

random_bytes(int $length): string

Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

Öncelik sırasına göre rastgelelik kaynakları aşağıdaki gibidir:

  • Linux: » getrandom(), /dev/urandom.

  • FreeBSD >= 12 (PHP >= 7.3): » getrandom(), /dev/urandom

  • Windows (PHP >= 7.2): » CNG-API

    Windows: » CryptGenRandom

  • macOS (PHP >= 8.2; >= 8.1.9; >= 8.0.22 if CCRandomGenerateBytes is available at compile time): CCRandomGenerateBytes()

    macOS (PHP >= 8.1; >= 8.0.2): arc4random_buf(), /dev/urandom

  • NetBSD >= 7 (PHP >= 7.1; >= 7.0.1): arc4random_buf(), /dev/urandom

  • OpenBSD >= 5.5 (PHP >= 7.1; >= 7.0.1): arc4random_buf(), /dev/urandom

  • DragonflyBSD (PHP >= 8.1): » getrandom(), /dev/urandom

  • Solaris (PHP >= 8.1): » getrandom(), /dev/urandom

  • Daha önce belirtilmeyen herhangi bir işletim sistemi ve PHP sürümü birleşimi: /dev/urandom
  • Kaynaklardan hiçbiri kullanılabilir değilse veya hiçbiri rasgelelik üretemezse, bir Random\RandomException oluşur.

Bilginize: Bu işlev PHP'ye PHP 7.0'da eklenmiş olsa da, » kullanıcı alanı gerçeklenimi PHP 5.2'den (dahil) 5.6'ya (dahil) kadar kullanılmıştır.

Bağımsız Değişkenler

length

The length of the random string that should be returned in bytes; must be 1 or greater.

Dönen Değerler

A string containing the requested number of cryptographically secure random bytes.

Hatalar/İstisnalar

Sürüm Bilgisi

Sürüm: Açıklama
8.2.0 In case of a CSPRNG failure, this function will now throw a Random\RandomException. Previously a plain Exception was thrown.

Örnekler

Örnek 1 random_bytes() example

<?php
$bytes
= random_bytes(5);
var_dump(bin2hex($bytes));
?>

Yukarıdaki örnek şuna benzer bir çıktı üretir:

string(10) "385e33f741"

Ayrıca Bakınız

add a note

User Contributed Notes 1 note

up
5
ccbsschucko at gmail dot com
5 years ago
<?php
   
function str_rand(int $length = 64){ // 64 = 32
       
$length = ($length < 4) ? 4 : $length;
        return
bin2hex(random_bytes(($length-($length%2))/2));
    }
   
   
var_dump(str_rand());
   
// d6199909d0b5fdc22c9db625e4edf0d6da2b113b21878cde19e96f4afe69e714
?>
To Top