Create/Call a Function so I don't have to insert the same code several times?

Wednesday, November 4, 2015

I have a very redundant code currently on my website.



This code allows me to display a functionnality for the user provided one of the following condition is met :




  • User has full rights

  • User has normal rights but is on his main repertory

  • User has normal rights but is on one of the subfolders of his main repertory



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);
?>


I'm still new in php and i was wondering if there is a way to simplify this, make the code less redundant, lighter, since I currently have to include this 8 times on my page.



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 !

0 comments:

Post a Comment