{"record":{"id":"e40f32a75e789801","repo":"paragonie/random_compat","slug":"random-bytes-bytes-must-be-an-integer","errorCode":null,"errorMessage":"random_bytes(): $bytes must be an integer","messagePattern":"random_bytes\\(\\): \\$bytes must be an integer","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"lib/random_bytes_com_dotnet.php","lineNumber":47,"sourceCode":"if (!is_callable('random_bytes')) {\n    /**\n     * Windows with PHP < 5.3.0 will not have the function\n     * openssl_random_pseudo_bytes() available, so let's use\n     * CAPICOM to work around this deficiency.\n     *\n     * @param int $bytes\n     *\n     * @throws Exception\n     *\n     * @return string\n     */\n    function random_bytes($bytes)\n    {\n        try {\n            /** @var int $bytes */\n            $bytes = RandomCompat_intval($bytes);\n        } catch (TypeError $ex) {\n            throw new TypeError(\n                'random_bytes(): $bytes must be an integer'\n            );\n        }\n\n        if ($bytes < 1) {\n            throw new Error(\n                'Length must be greater than 0'\n            );\n        }\n\n        /** @var string $buf */\n        $buf = '';\n        if (!class_exists('COM')) {\n            throw new Error(\n                'COM does not exist'\n            );\n        }\n        /** @var COM $util */","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/paragonie/random_compat/blob/b5d188cc9d5e02f94d2c41da23093f1ef557c5b1/lib/random_bytes_com_dotnet.php#L29-L65","documentation":"random_bytes() first coerces its argument with RandomCompat_intval(), which throws TypeError for values that cannot be losslessly converted to a non-negative-safe integer (floats with fractions, non-numeric strings, objects, arrays, null). The library catches that internal TypeError and rethrows a clearer one so the caller knows the $bytes parameter itself is bad. This is a fail-fast contract check mirroring PHP 7's native random_bytes() signature.","triggerScenarios":"Calling random_bytes() with a non-integer value: a numeric string like '10' in strict setups that fail intval conversion, a float such as 10.5, null, a boolean, an array, or an object lacking a valid __toString/to-int path that RandomCompat_intval() rejects.","commonSituations":"Passing user-supplied request input or unvalidated JSON/GET/POST values straight into random_bytes(); forwarding the result of a calculation that returned null on failure; PHP 5.x polyfill usage where no native type declarations protect the call site.","solutions":["Cast or validate the length to a positive integer before calling: $len = (int) $len;","Add a type guard: if (!is_int($len) || $len < 1) { throw new InvalidArgumentException(...); }","Use RandomCompat_intval() or PHP's is_int()/ctype_digit() checks on any dynamic input.","Pass a literal integer constant for fixed sizes (e.g. random_bytes(32))."],"exampleFix":"// before\n$token = random_bytes($_GET['length']);\n// after\n$length = filter_var($_GET['length'], FILTER_VALIDATE_INT);\nif ($length === false || $length < 1) {\n    throw new InvalidArgumentException('length must be a positive integer');\n}\n$token = random_bytes($length);","handlingStrategy":"type-guard","validationCode":"function ensureRandomLength($len) {\n    if (!is_int($len) || $len < 1) {\n        throw new InvalidArgumentException('random_bytes length must be a positive integer');\n    }\n    return $len;\n}","typeGuard":"function isValidRandomLength($len) {\n    return is_int($len) && $len >= 1;\n}","tryCatchPattern":"try {\n    $bytes = random_bytes($len);\n} catch (TypeError $e) {\n    // $len was not an integer; log and fail the request\n    throw new InvalidArgumentException('invalid random_bytes length', 0, $e);\n}","preventionTips":["Never pass raw request input to random_bytes(); cast and validate first.","Enable PHP 7+ strict_types and scalar type hints (int $len) at call sites.","Use filter_var($v, FILTER_VALIDATE_INT) for external values.","Centralize byte-length generation in one helper that validates once."],"tags":["php","type-error","argument-validation","random-bytes"],"backgroundTag":"invalid-argument-value","analyzedSha":"b5d188cc9d5e02f94d2c41da23093f1ef557c5b1","analyzedAt":"2026-09-13T16:12:09.755Z","contentChangedAt":"2026-09-13T16:12:09.755Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}