JoJ*_*Dad 19 php parameters require include
我已经阅读了很多与我要提出的问题非常相似的帖子,但我只是想确保没有更复杂的方法来做到这一点.任何反馈都非常感谢.
我想创建一种机制来检查登录用户是否可以访问当前正在调用的php脚本.如果是这样,脚本将继续; 如果没有,脚本就会失败,使用类似的东西die('you have no access').
我想出了两种方法来完成这个:
(请假设我的会话内容已编码/工作正常 - 即我调用session_start(),正确设置会话变量等)
首先定义一个全局变量,然后检查所需头文件中的全局变量.例如:
current_executing_script.php的内容:
// the role the logged in user must have to continue on
$roleNeedToAccessThisFile = 'r';
require 'checkRole.php''
Run Code Online (Sandbox Code Playgroud)
checkRole.php的内容:
if ($_SESSION['user_role'] != $roleNeedToAccessThisFile) die('no access for you');
Run Code Online (Sandbox Code Playgroud)在头文件中定义一个函数,并在包含/要求后立即调用该函数:
checkRole.php的内容:
function checkRole($roleTheUserNeedsToAccessTheFile) {
return ($_SESSION['user_role'] == $roleTheUserNeedsToAccessTheFile);
}Run Code Online (Sandbox Code Playgroud)
current_executing_script.php的内容:
require 'checkRole.php';
checkRole('r') or die('no access for you');Run Code Online (Sandbox Code Playgroud)我想知道是否有一种方法基本上只是将参数传递给checkRole.php作为include或require构造的一部分?
提前致谢.
Spu*_*ley 36
没有办法将参数传递给include或require.
但是,包含的代码在包含它的位置加入程序流,因此它将继承范围内的任何变量.因此,例如,如果您在include之前立即设置$ myflag = true,那么您包含的代码将能够检查$ myflag的设置.
也就是说,我不建议使用这种技术.包含文件包含函数(或类)而不是直接运行的代码要好得多.如果你已经包含了一个包含函数的文件,那么你可以在程序的任何一点用你想要的任何参数调用你的函数.它更灵活,通常是更好的编程技术.
希望有所帮助.
这是我在最近的 Wordpress 项目中使用的东西
做一个功能functions.php:
function get_template_partial($name, $parameters) {
// Path to templates
$_dir = get_template_directory() . '/partials/';
// Unless you like writing file extensions
include( $_dir . $name . '.php' );
}
Run Code Online (Sandbox Code Playgroud)
获取参数cards-block.php:
// $parameters is within the function scope
$args = array(
'post_type' => $parameters['query'],
'posts_per_page' => 4
);
Run Code Online (Sandbox Code Playgroud)
调用模板index.php:
get_template_partial('cards-block', array(
'query' => 'tf_events'
));
Run Code Online (Sandbox Code Playgroud)
例如,显示的帖子总数:
改成functions.php这样:
function get_template_partial($name, $parameters) {
// Path to templates
$_dir = get_template_directory() . '/partials/';
// Unless you like writing file extensions
include( $_dir . $name . '.php' );
return $callback;
}
Run Code Online (Sandbox Code Playgroud)
改成cards-block.php这样:
// $parameters is within the function scope
$args = array(
'post_type' => $parameters['query'],
'posts_per_page' => 4
);
$callback = array(
'count' => 3 // Example
);
Run Code Online (Sandbox Code Playgroud)
改成index.php这样:
$cardsBlock = get_template_partial('cards-block', array(
'query' => 'tf_events'
));
echo 'Count: ' . $cardsBlock['count'];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30786 次 |
| 最近记录: |