是否可以检测何时包含php文件?
因此,在文件是否可以检测何时包含php文件?,php,Php,因此,在文件first.php中,我将把文件original.php包含在include\u once中 当我试图调用original.php中的函数时,出现了问题,如果没有用户会话,该文件就不会加载 基本上我包含了文件original.php,其中有几个函数我稍后在first.php中调用,但是由于我在original.php中设置的限制,这些函数是不可使用的,但现在我想向original.php添加规则,以允许来自first.php或任何其他包含original.php的php文件的此类请求
first.php
中,我将把文件original.php
包含在include\u once
中
当我试图调用original.php
中的函数时,出现了问题,如果没有用户会话,该文件就不会加载
基本上我包含了文件original.php
,其中有几个函数我稍后在first.php
中调用,但是由于我在original.php
中设置的限制,这些函数是不可使用的,但现在我想向original.php
添加规则,以允许来自first.php
或任何其他包含original.php
的php文件的此类请求
我想知道在这种情况下我能做些什么,或者我能简单地在original.php
中添加一些if子句,比如:
if($fileIncluded == 'yes')
{
// do not check if user session exist etc.
}
else
{
// check for user session
}
提前感谢您的想法和帮助 嗯,我是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提供了一个函数,在这种情况下似乎可以工作
if in_array('file.php', get_included_files()) {
/* ... */
}
您可以在文件中设置要包括的常量,如下所示: 在
original.php
中:
define('ORIGINAL_INCLUDED', TRUE);
if ('original.php' == basename(__FILE__))
{
// original.php directly accessed
}
else
{
// original.php included instead
}
然后在first.php
中检查常量是否存在:
if (defined('ORIGINAL_INCLUDED'))
{
// do not check if user session exist etc.
}
else
{
// check for user session
}
与此不同,当脚本包含脚本时,此选项将起作用get_included_files()
只返回主脚本中包含的文件,而不返回子脚本中包含的脚本
或者在original.php
中:
define('ORIGINAL_INCLUDED', TRUE);
if ('original.php' == basename(__FILE__))
{
// original.php directly accessed
}
else
{
// original.php included instead
}
您还可以定义一个常量,并检查它是否在以后定义。使用define和defined函数。我认为这比使用正态变量要好
Php doc:和代码必须位于original.Php文件中…:你理解错了。你是说如果没有用户会话,你故意不包括
original.php
,或者即使你调用include\u一次,如果用户会话不存在,它也不包括它?这听起来像是你代码中的一个bug。感谢你的贡献,我已经更新了我的原始帖子来解释我想要实现的目标。再次感谢!谢谢你的贡献,我已经更新了我原来的帖子来解释我想要达到的目标。再次感谢+1对于C风格的方法,虽然它在PHP中看起来有点混乱。我想检测文件是否包含在原始文件中。php@Adrov那么您将first.php
包含到original.php
中了吗?如果是这样,请参阅我的编辑。否,我将original.php
包含在first.php
中,我只想在original.php
中添加一个规则/检查,如果可能的话,当文件被包含且未直接加载到浏览器中时,它将跳过所有检查,例如(用户登录、管理员会话等)我不确定这是否可能,这就是为什么我要问:)如果我正确理解你,上面的@Adrov应该足够了。