繁体   English   中英

来自根目录的PHP警告

[英]PHP warning from root directory

我的php代码有问题。

文件夹名称 what-c​​ounter此文件夹包含一个文件,其中包含以下名为counter.php的php代码以及hitcount.txt文件。

<?php

$filename = '../what-counter/hitcount.txt';
$handle = fopen($filename, 'r');
$hits = trim(fgets($handle)) + 1;
fclose($handle);

$handle = fopen($filename, 'w');
fwrite($handle, $hits);
fclose($handle);

// Uncomment the next line (remove //) to display the number of hits on your page.
echo $hits;

?>

以下php代码用于根目录文件中,也用于回显命中的文件夹中的文件中。

<?php include("../what-counter/counter.php"); ?>

问题代码在文件夹中的文件中起作用,但在直接位于根目录中的文件中则无效。 示例:index.php在根目录中

使用此代码我得到此警告

<?php include("what-counter/counter.php"); ?>

Warning: fopen(../what-counter/hitcount.txt) [function.fopen]: failed to open stream: No such file or directory in /home/what/public_html/what-counter/counter.php on line 4

Warning: fgets(): supplied argument is not a valid stream resource in /home/what/public_html/what-counter/counter.php on line 5

Warning: fclose(): supplied argument is not a valid stream resource in /home/what/public_html/what-counter/counter.php on line 6

Warning: fopen(../what-counter/hitcount.txt) [function.fopen]: failed to open stream: No such file or directory in /home/what/public_html/what-counter/counter.php on line 8

Warning: fwrite(): supplied argument is not a valid stream resource in /home/what/public_html/what-counter/counter.php on line 9

Warning: fclose(): supplied argument is not a valid stream resource in /home/what/public_html/what-counter/counter.php on line 10

并使用此代码我得到此警告

<?php include("../what-counter/counter.php"); ?>

Warning: include(../what-counter/counter.php) [function.include]: failed to open stream: No such file or directory in /home/what/public_html/include/footer.php on line 31

Warning: include(../what-counter/counter.php) [function.include]: failed to open stream: No such file or directory in /home/what/public_html/include/footer.php on line 31

Warning: include() [function.include]: Failed opening '../what-counter/counter.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/what/public_html
/include/footer.php on line 31

我可以对$ filename url和<?php include("../what-counter/counter.php"); ?> <?php include("../what-counter/counter.php"); ?>得到它在文件中工作,根目录以及文件夹?

要么:

  • 包括相对文件: __DIR__.'/../somefile'; / __DIR__.'/somepath/somefile';
  • 相对于已知目录的包含:通常使用$_SERVER['DOCUMENT_ROOT'] ,以及引导程序代码中类似于PROJECT_DIRdefine()
  • 将工作目录更改为已知/静态目录chdir('/some/dir'); 不建议使用此代码,因为调用代码可能不会这样。

听起来像是绝对文件还是相对文件问题...

尝试更换:

$filename = '../what-counter/hitcount.txt';

使用以下方法之一,取决于文件的确切位置:

$filename = __DIR__ . '/what-counter/hitcount.txt';
$filename = dirname(__DIR__) . '/what-counter/hitcount.txt';

或者(如果您使用的是旧版php):

$filename = dirname(__FILE__) . '/what-counter/hitcount.txt';
$filename = dirname(dirname(__FILE__)) . '/what-counter/hitcount.txt';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM