我的php代码有问题。
文件夹名称 what-counter此文件夹包含一个文件,其中包含以下名为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"); ?>
做什么让它在根目录和文件夹中的文件中工作?
答案 0 :(得分:0)
或者:
__DIR__.'/../somefile';
/ __DIR__.'/somepath/somefile';
$_SERVER['DOCUMENT_ROOT']
经常被用作PROJECT_DIR
- 就像您的引导代码中的define()
一样。chdir('/some/dir');
。不推荐使用,因为调用代码可能不会这样。答案 1 :(得分:0)
听起来像绝对vs相对文件问题......
尝试更换:
$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';