2013-06-22 67 views
0

我有一個php代碼的問題。根目錄下的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 

能有什麼我做到$文件名的URL和<?php include("../what-counter/counter.php"); ?>讓它在根目錄以及文件夾中的文件中工作?

+0

如果我刪除../從文件和包含它在index.php頁面上工作,但不在文件夾文件中,所以這是與../ – mally

回答

0

或者:

  • 包括相對的文件:__DIR__.'/../somefile';/__DIR__.'/somepath/somefile';
  • 包括相對於已知DIR:$_SERVER['DOCUMENT_ROOT']經常使用,因爲是PROJECT_DIRdefine()在你的引導代碼。
  • 將工作目錄更改爲已知/靜態目錄chdir('/some/dir');。不建議調用代碼可能不期望這一點。
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';