我有一个函数可以检查用户是否在一个库中拥有正确的权限,如果用户有,我希望它设置一个新变量:getprivileges = true
<?php
$directory = $_SESSION['cwd']; // current directory
$user = $_SESSION['simple_auth']['username']; // get username
$repository = gatorconf::get('repository'); // get base repertory of the file manager
$userdir = $repository.DS.'user'.DS.$user; // user's repertory
function scanDirectory($userdir = '', $directory){
$folders = glob($userdir . '/*' , GLOB_ONLYDIR);
foreach($folders as $folder){
if (($folder == $directory && gator::checkPermissions('r')) || (gator::checkPermissions('ru')) || ($userdir == $directory && gator::checkPermissions('r'))) {
$getprivileges = true;
break;
}
scanDirectory($folder, $directory);
}
}
scanDirectory($userdir, $directory);
?>
<?php if ($getprivileges == true): ?>
<p>Permissions granted.<p>
<?php endif; ?>
我相信功能return
正是我想要的,但我真的不知道如何使用它。
代码的最后一部分只是我的目标是用我的变量做的例子。
我补充说到目前为止我的变量$ getprivileges没有在我的代码中的任何其他地方定义,所以也许我必须首先给它一个默认值?
有人可以给我一些关于我如何做到这一点的解释吗?
非常感谢
解决方案更新评论:
<?php
$directory = $_SESSION['cwd']; // current directory
$user = $_SESSION['simple_auth']['username']; // get username
$repository = gatorconf::get('repository'); // get base repertory of the file manager
$userdir = $repository.DS.'user'.DS.$user; // user's repertory
$getprivileges = scanDirectory($userdir, $directory);
function scanDirectory($userdir = '', $directory){
$folders = glob($userdir . '/*' , GLOB_ONLYDIR);
foreach($folders as $folder){
if (($folder == $directory && gator::checkPermissions('r')) || (gator::checkPermissions('ru')) || ($userdir == $directory && gator::checkPermissions('r'))) {
return true;
break;
}
scanDirectory($folder, $directory);
}
}
scanDirectory($userdir, $directory);
?>
<?php if ($getprivileges == true): ?>
<p>Permissions granted.<p>
<?php endif; ?>
答案 0 :(得分:1)
我将其设为社区维基,因为作者已经找到了解决方案。
你是正确的,你需要使用return
。通过使用return
,您可以返回一些值作为函数调用的值,并将该值赋给变量。在您的情况下,您想要返回true
或false
。
然后你可以这样设置$getprivileges
:
$getprivileges = scanDirectory($userdir, $directory);
你的功能应该是这样的:
function scanDirectory($userdir = '', $directory){
$folders = glob($userdir . '/*' , GLOB_ONLYDIR);
foreach($folders as $folder){
if (($folder == $directory && gator::checkPermissions('r')) || (gator::checkPermissions('ru')) || ($userdir == $directory && gator::checkPermissions('r'))) {
// Replaced here.
return true;
}
scanDirectory($folder, $directory);
}
// Added here.
return false;
}