今天我收到来自我的 Web 服务器管理员的电子邮件,说"由于大约 60 GB 的错误文件,您的服务已暂停。检查错误日志.txt通过 FTP 检查。在日志文件中,只有以下两行重复:
[Tue Apr 04 08:45:52 2017] [error] [client xxx.xxx.xxx.xxx] PHP Warning: feof() expects parameter 1 to be resource, boolean given in /var/www/vhosts/.../httpdocs/dene.php on line 11
[Tue Apr 04 08:45:52 2017] [error] [client xxx.xxx.xxx.xxx] PHP Warning: fgetc() expects parameter 1 to be resource, boolean given in /var/www/vhosts/.../httpdocs/dene.php on line 13
这是相关的代码片段:
<?
header("X-XSS-Protection: 0");
$filename= $_GET['filename'];
$code = $_POST['code'];
if (isset($filename))
{
$go = $filename;
$full = "docs/$filename.htm";
$filename = @fopen($full , 'r');
$file_size = filesize($full);
while (! feof($filename)) //line 11
{
$char = fgetc ($filename); //line13
$code .= "$char";
}
fclose($filename);
}
$code = str_replace("\", "", $code);
$code = str_replace(">", ">", $code);
$code = str_replace("=", "=", $code);
$code = str_replace("<", "<", $code);
printf("%s",$code);
?>
这里有什么问题?提前感谢...
您需要检查fopen
结果。
$resource = @fopen($filename , 'r');
if ( $resource ) {
while (! feof($resource))
{
...
}
}
来自 PHP 手册:
<?php
// if file can not be read or doesn't exist fopen function returns FALSE
$file = @fopen("no_such_file", "r");
// FALSE from fopen will issue warning and result in infinite loop here
while (!feof($file)) {
}
fclose($file);
?>
您
收到这些错误是因为您没有在feof
和fgetc
中将有效的资源作为参数传递。应确保在以下位置传递有效的文件指针:
$filename = @fopen($full , 'r');
您应该确保:
- 您尝试打开的文件存在
- 并且它具有正确的权限。(如果需要,CHMOD 775(
如果上述之一失败,$filename将返回false
。您还可以改进代码逻辑以处理此错误情况,如下所示:
$filename = @fopen( $full, 'r' );
// Make sure we have a valid file resource
if ( $filename ) {
$file_size = filesize( $full );
while ( ! feof( $filename ) )
{
$char = fgetc( $filename );
$code .= "$char";
}
fclose( $filename );
} else {
// Not a valid file resource
die( "This file resource could not be open." );
}
注意:$filename
实际上不是正确的变量名称,则应将其重命名为$filePointer
或$fp