0

我的 php 代码有问题。

文件夹名称what-c​​ounter 该文件夹包含一个带有以下 php 代码的文件 counter.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"); ?>让它在根目录和文件夹中的文件中工作?

4

2 回答 2

0

任何一个:

  • 包含相对文件:__DIR__.'/../somefile';/__DIR__.'/somepath/somefile';
  • Include relative to a known dir:$_SERVER['DOCUMENT_ROOT']经常使用,就像引导代码中的 -likePROJECT_DIR一样。define()
  • 将工作目录更改为 known/static dir chdir('/some/dir');。不推荐,因为调用代码可能不会想到这一点。
于 2013-06-22T15:17:43.960 回答
0

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

尝试更换:

$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';
于 2013-06-22T15:17:47.840 回答