簡體   English   中英

是否可以檢測何時包含php文件?

[英]Is it possible to detect when php file is included?

所以在文件first.php我將包含文件original.phpinclude_once

當我嘗試調用original.php函數並且如果沒有用戶會話則沒有加載該文件時,會出現問題。

Basicaly我包含文件original.php ,其中很少有函數我稍后在first.php調用,但是這些函數由於我在original.php設置的限制而無法訪問,但現在我想將規則添加到original.php允許來自first.php或任何其他包含original.php PHP文件的請求...

我想知道在這種情況下我能做什么或者我可以簡單地將一些if子句添加到original.php ,例如:

if($fileIncluded == 'yes')
{
   // do not check if user session exist etc.
}
else
{
   // check for user session
}

感謝您的想法和提前幫助!

您可以在文件中設置一個常量,如下所示:

original.php

define('ORIGINAL_INCLUDED', TRUE);

然后在first.php檢查常量是否存在:

if (defined('ORIGINAL_INCLUDED'))
{
    // do not check if user session exist etc.
}
else
{
    // check for user session
}

get_included_files()不同,當腳本包含腳本時,這將起作用。 get_included_files()只返回主腳本中包含的文件,但不返回子腳本中包含的腳本。

或者在original.php

if ('original.php' == basename(__FILE__))
{
    // original.php directly accessed
}
else
{
    // original.php included instead
}

PHP提供了一個get_included_files函數,在這種情況下似乎可以正常工作。

if in_array('file.php', get_included_files()) {
    /* ... */
}

好吧,我是PHP新手,但我會這樣做

$add_file = require(file.php);

然后呢

if($add_file) {echo "file is aded";} else {echo "file is not added";}

您可以使用函數get_included_files()或設置如下變量:

  // includedfile.php
 $variable = true;

 //index.php
 include 'includedfile.php';

 if(isset($variable)) {
     // file included
 } else {
     // not included
 }

您還可以定義一個常量,並檢查它是否稍后定義。 使用定義定義的函數。 我認為這比使用普通變量更好。

Php doc: http//ch2.php.net/manual/en/function.defined.phphttp://ch2.php.net/manual/en/function.define.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM