2012-12-18 20 views
2

創建一個包括2個文件PHP項目 - index.php包含下面的代碼和其他文件(在相同的目錄)稱爲example.png關機處理程序和相對路徑

echo file_exists('example.png') 
    ? 'outside the handler - exists' 
    : 'outside the handler - does not exist'; 

register_shutdown_function('handle_shutdown'); 

function handle_shutdown() 
{ 
    echo file_exists('example.png') 
     ? 'inside the handler - exists' 
     : 'inside the handler - does not exist'; 
} 

foo(); 

運行index.php

這裏就是你會得到什麼:

outside the handler - exists 
Fatal error: Call to undefined function foo() in /path/to/project/index.php on line 16 
inside the handler - does not exist 

這裏是我的問題。

爲什麼不能內部file_exists(一個在處理程序),找到該文件?

+0

example.php or example.png? – rendon

+0

這是衆所周知的不起作用。您需要在PHP的關閉階段使用絕對路徑。請參閱http://php.net/register_shutdown_function上的註釋 – hakre

+0

這可能是一個錯字,但是從輸出中可以看到,同一個文件存在檢查返回handle_shutdown函數內外的不同值 –

回答

2

我不知道是什麼原因的原因,但PHP文件並在register_shutdown_function()下的說明其中規定警告這樣的:

Note: 

Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache. 

你可以嘗試呼應了getcwd()得到一個想法,什麼是真正發生。

+0

如果工作目錄確實發生變化,這裏有一個解決方案的鏈接。 http://stackoverflow.com/questions/10861606/write-to-file-with-register-shutdown-function –

1

在PHP的一些SAPI上,在關閉功能中工作目錄可以改變。見register_shutdown_function的手冊上這樣一個字條:

工作腳本的目錄可以在某些Web服務器的關機功能內改變,例如Apache的。

相對路徑是依賴於工作目錄。隨着它的改變,該文件不再被發現。

如果使用絕對路徑,而不是,你不會遇到這個問題:

$file = __DIR__ . '/' . 'example.png'; 

echo file_exists($file) 
    ? 'outside the handler - exists' 
    : 'outside the handler - does not exist'; 

$handle_shutdown = function() use ($file) 
{ 
    echo file_exists($file) 
     ? 'inside the handler - exists' 
     : 'inside the handler - does not exist'; 
} 

register_shutdown_function($handle_shutdown);