some background : My webste integrates a File Manager (FileGator) that allows users to consult the files present in it, and also functionnalities like upload/move/create or delete files. The code I'm working on determines the privileges of the current user and only displays the functionnalities if he has the rights privileges.
When a user registers on the website, a repertory $userdir
is created in which the member is granted functionnalities privileges. The code that allows me to display a functionnality for the user checks if one of thoses conditions is met :
- User has full rights
- User has normal rights but is on his main repertory
( /user/$userdir )
- User has normal rights but is on one of the subfolders of his main repertory
( /user/$userdir/subfolder1 )
So currently I have to repeat the full code for every functionnality (about eight).
Here is my code, with the upload functionnality :
<?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'))): ?>
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="fileinput-button nice radius button">
<i class="icon-plus icon-white"></i>
<span class=""><?php echo lang::get("Add Files...")?></span>
<input type="file" name="files[]" multiple>
<input type="hidden" name="uniqid" value="50338402749c1">
</span>
<?php break; endif;
scanDirectory($folder, $directory);
}
}
scanDirectory($userdir, $directory);
?>
The only part of this code that changes is the HTML code inside the If condition, in my exemple this was the HTML to display the Upload functionnality. The code works fine but currently the same code is repeated for every functionnality in the page, while only the HTML part of the code is changing.
I'm still new in php and I was wondering if there is a way to simplify this, make the code less redundant.
Is there a way to transorm this into some kind of function ? Like write the full code once in a function.php file and then call it on my main page where i would only add he code of the functionnality.
Hope this is clear enough since I'm too sure if that is possible.
Thanks !