-1
public function getRandomStr() {
    return bin2hex(file_get_contents('/dev/urandom', 0, null, -1, 16));
}

im trying to retrieve a random 32 character string here but I keep getting the above error, I did look to relevant posts but they all say that this is a offset error while I changed the offset from -1 to 1 and it didn't change anything, does anybody know why this error occurs in the first place.

phperson
  • 21
  • 7
  • 1
    _"I changed the offset from -1 to 1 and it didn't change anything"_ - of course it doesn't. It does not matter which _direction_ you attempt to seek in - not seekable means not seekable. – CBroe Aug 18 '23 at 13:16
  • 1
    https://stackoverflow.com/a/8429944/1427878 has an example how to read a given number of bytes from /dev/urandom using fopen/fread/fclose. – CBroe Aug 18 '23 at 13:18
  • I tought it was related to file perms, let me check bellow on reading /dev/urandom, never saw it before. – phperson Aug 18 '23 at 13:20
  • @CBroe what is $len supposed to be in the example? – phperson Aug 18 '23 at 13:23
  • The number of characters you want to read. – CBroe Aug 18 '23 at 13:30
  • Why not just use [`random_bytes()`](https://www.php.net/manual/en/function.random-bytes.php)? `return bin2hex(random_bytes(16));` – user1191247 Aug 18 '23 at 13:43

1 Answers1

1

There is no use of seeking in /dev/urandom (cf. urandom(4), it is a special device file (major device number 1 and minor device number 9) that provides an interface to the kernel's random number generator.

What its for is that you read from it, not seek it.

While earlier versions of PHP had no problem to run file_get_contents() with offset: -1, there actually is no issue here in using the offset zero, as length: 16 remains the same.

Update your code by using offset: 0:

$result = file_get_contents('/dev/urandom', 0, null, 0, 16);
                                                     #

$result remains on strlen($result): 16, as earlier.


If you don't have the requirement working with the device file specifically, you can find the general interface in PHP with random_bytes():

$result = random_bytes(16);

https://php.net/random_bytes

hakre
  • 193,403
  • 52
  • 435
  • 836