PHP Warning: fread(): Length parameter must be greater than 0 in setoptions.php on line 311 Error and Solution

last updated in Categories ,

One of my php script called setoptions.php is hosted on my new vps server. However, it is not working so I setup php error log as described here and, and I see the following warning repeated in my log file:

PHP Warning: fread(): Length parameter must be greater than 0 in /var/www/html/scripts/setoptions.php on line 311

The line no # 311 is as follows in my php script:
$fname = 'myappconfig.php';
$content = fread($fhandle,filesize($fname));

How do I fix this problem under Unix/Apache/php5 server?

To fix this problem, try the following solutions:

[1] Make sure file $fname exists i.e. myappconfig.php is in path.

[2] Make sure file myappconfig.php has correct permission. Apache or any other webserver needs read-only permission for reading file.

[3] Make sure file myappconfig.php exists and size is not zero i.e. make sure file is not empty.

[4] Use is_readable() to find out whether a file exists and is readable:

$fname = 'myappconfig.php';
if (is_readable($fname)) {
    $content = fread($fhandle,filesize($fname));
} else {
    echo 'The file is not readable.';

(Listing 01: is_readable() php sample code )

[5] Also use file_exists() to check whether a file or directory exists:

$fname = 'myappconfig.php';
if (file_exists($fname)) {
    // do_something like as follows?
    // $content = fread($fhandle,filesize($fname));
} else {
    echo "The file $fname does not exist.";

(Listing 02: file_exists() php sample code )

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

1 comment

  1. Or, you could simply:

    $file_size = filesize($fname);
    //We are clearly greater than 0 now, as 0 = false to PHP
    $content = fread($fhandle,$file_size);
    throw new Exception(“An error occurred reading $fname”);

    Still, have a question? Get help on our forum!