Last updated: November 27, 2026.
Validate a file read length before passing it to PHP. A nonpositive fgets() length or negative file_get_contents() length can throw ValueError instead of returning false. An empty string can still be valid output.
<?php
function readFilePreview(string $trustedPath, int $bytes): string
{
if ($bytes < 0 || $bytes > 65536) {
throw new InvalidArgumentException('Preview must be 0 to 65536 bytes');
}
if ($bytes === 0) {
return '';
}
$contents = file_get_contents($trustedPath, length: $bytes);
if ($contents === false) {
throw new RuntimeException('Could not read the preview file');
}
return $contents;
}Choose the limit for the function
The file_get_contents() length is a maximum number of bytes to read. The preview function defines zero as a request for an empty preview and returns before opening the file. It rejects negative values and caps the read so a caller cannot request a huge preview. Use a path selected by the application, such as a file mapped from a known report ID.
With fgets(), a positive length sets a ceiling of length - 1 bytes. Use at least two if the read should be able to consume a byte. A read can also stop sooner at a newline or EOF. If line length is already bounded by your input format, you can omit the length to read a whole line.
Keep argument errors and read failures separate
Check return values using === false. A file may be empty or contain the string 0 and both are legitimate results. After fgets() returns false, feof() helps distinguish an exhausted stream from a possible read failure. A missing or inaccessible file can produce a warning and false in an ordinary file_get_contents() call.
A ValueError indicates that PHP rejected an argument value. Correct the limit at its source rather than interpreting the exception as EOF. For previews of UTF-8 text, remember that the limit counts bytes. A preview boundary can fall in the middle of a character.