The following code is meant to display directories as well as sub directories within the directories and the files inside them. I used chmod function to gain access to directories.
This code runs but doesn't display the directory hierarchy, which means it is unable to list the sub directories and the files inside.
As I run the script, I get this warning :
Warning: chmod(): No such file or directory in E:\Installed_Apps\xampp\htdocs\dlist.php on line 5
-
#recursive function
function directory_f_lister($root) {
$dir_list = scandir($root);
for($var=0;$var<count($dir_list);$var++) {
$bool = chmod($root.$dir_list[$var], 0777);
if(is_readable($root.$dir_list[$var])) {
if(is_dir($root.$dir_list[$var])) {
if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
echo "<h3>Name of directory $dir_list[$var]</h3>";
echo "<br />";
$dh = opendir($root.$dir_list[$var]);
while(($name = readdir($dh)) !== false) {
if(is_dir($root.$dir_list[$var].$name)) {
if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
echo "Name of directory : <strong> $name </strong>";
echo "<br />";
directory_f_lister($root.$dir_list[$var].$name);
}else {
echo $name;
echo "<br/>";
}
}
}
} else { "<b>else statement <br /> </b>"; }
}
}
directory_f_lister(DIRECTORY_SEPARATOR);
What is the problem ? Why am I not getting the directory hierarchy ?
chmod(realpath(dirname(__FILE__)).'/'.$dir_list[$var], 0777);
Related
I want to display the links separately. One list would include all the .html links and the other all the .jpg links.
right now it displays this and I understand why it is doing it, but when i do another foreach outside or even right before the echo, its like nothing is passing into it.
.jpg
.html
.jpg
.html
I need it to display like this
HTML-Backup HTML
.jpg .html
.jpg .html
php Code
$array = array();
$html= "";
$htmlBackup= "";
if(file_exists("uploads/" . $_POST["prefix"] .'/'))
{
$dir = 'uploads/' . $_POST["prefix"] . '/';
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir));
$prefixDir = scandir($dir);
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.' </br>';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.' </br>';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
}
}
}
Don't put <br> at the end of each echo. Do it after the inner loop so all links from the same directory will be on the same line.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.jpg") !== false)
{
echo''.$lastDir.'';
//variable to store list of dir
$html=$lastDir;
} else if(strpos($lastDir, "HTML5.html") !== false )
{
echo''.$lastDir.'';
//variable to store the list of dir
$htmlBackup=$lastDir;
}
}
echo "<br>";
}
}
I found a solution by including arrays.
foreach($prefixDir as $dir_files)
{
$secondDir = $dir . $dir_files;
//$finalDir=scandir($secondDir);
if((is_dir($secondDir)))
{
$finalDir=preg_grep('~\.(html|jpg)$~', scandir($secondDir));
$i = 0;
foreach($finalDir as $lastDir)
{
if(strpos($lastDir, "HTML5.html") !== false || strpos($lastDir, "H5.html") !== false)
{
//variable to store the list of dir
array_push($html_array, $lastDir);
array_push($html_dir,$secondDir.'/'.$lastDir);
}
else if(strpos($lastDir, "HTML5.jpg") !== false || strpos($lastDir, "H5.jpg")!== false )
{
//variable to store list of dir
array_push($html_backup_array, $lastDir);
array_push($html_backup_dir,$secondDir.'/'.$lastDir);
}
}
}
}
and then display them under in another foreach as I want
if(!empty($html_array))
{
echo "<p>";
echo ("<p><span class='heading'>HTML5 Units</span></p>");
foreach (array_combine($html_dir, $html_array) as $html_dirr => $html_arrays)
{
echo (''.$html_arrays.'');
echo "<br>";
}
echo "</p>";
}
I have following PHP function which return all the folder with files in html li element from a given path.
function folderTree ($directory_path) {
if(!file_exists($directory_path)) {
die("The file $directory_path is not exists");
}
if(!is_dir($directory_path)) {
die("This directory $directory_path can't open");
}
$directory = opendir($directory_path);
$filenames = [];
while ($filename = readdir($directory)) {
if($filename !== '.' && $filename !== '..') {
if(is_dir($directory_path.'/'.$filename)) {
$filename .= '/';
}
$filenames[] = $filename;
}
}
echo "<ul>";
foreach ($filenames as $filename) {
echo "<li><a href='{$directory_path}/{$filename}'>";
echo $filename;
if(substr($filename, -1) == '/' ) {
folderTree($directory_path.'/'.substr($filename, 0, -1)).'/lv2/';
}
echo "</a></li>";
}
echo "</ul>";
}
now It's working fine and the output this below:
img-01
img01.jpg
img02.jpg
img03.jpg
img-02
img01.jpg
img02.jpg
img03.jpg
img-03
img01.jpg
img02.jpg
img03.jpg
This img-01, 02 and 03 is a folder and there are .jpg files exist.
Now, You can see the code above that it's wrapping all the files of all folders in a single ul element, right.
But I want it should wrap each folder by folder not all at once.
Now the code output is something like that:
<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li><li>jpg...</li> só on..</ul>
But I need:
<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li></ul>
<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li></ul>
<ul><li>jpg...</li><li>jpg...</li><li>jpg...</li></ul>
I have found a script that lists all directories and files in them, and allows for the deletion of files.
I have two problems:
1) How do I add the function to delete a folder (With all the contents in it)
2) How do I make the script not to allow a user to browse up a directory? (For e.g. a user's folder is ./files/$userid/. I want it so that a user won't be able to go to or make any changes to ./files/ or a folder other then ./files/$userid/
$script = basename(__FILE__); // the name of this script
$path = !empty($_REQUEST['path']) ? $_REQUEST['path'] : dirname('./files/' . (string)$userid . '/'); // the path the script should access
$unlink = $_REQUEST['unlink'];
if(!empty($unlink)){
$unlink = realpath("$path/$unlink");
if(is_writable($unlink) && !unlink($unlink)){
echo "<div class=\"error\">Unable to delete file: $unlink</div>";
}
}
echo "<p>Browsing Location: {$path}</p>";
$directories = array();
$files = array();
// Check we are focused on a dir
if (is_dir($path)){
chdir($path); // Focus on the dir
if ($handle = opendir('.')){
while (($item = readdir($handle)) !== false) {
// Loop through current directory and divide files and directorys
if(is_dir($item)){
array_push($directories, realpath($item));
}
else{
array_push($files, ($item));
}
}
closedir($handle); // Close the directory handle
}
else {
echo "<p class=\"error\">Directory handle could not be obtained.</p>";
}
}
else{
echo "<p class=\"error\">Path is not a directory</p>";
}
// List the directories as browsable navigation
echo "<h2>Navigation</h2>";
echo "<ul>";
foreach($directories as $directory){
$delete = is_writable($file) ? "<a class=\"unlink\" href=\"{$script}?path={$path}&unlink={$directory}\">delete</a>" : '';
echo ($directory != $path) ? "<li>{$directory}</li>" : "";
}
echo "</ul>";
echo "<h2>Files</h2>";
echo "<ul>";
foreach($files as $file){
// Comment the next line out if you wish see hidden files while browsing
if(preg_match("/^\./", $file) || $file == $script){continue;} // This line will hide all invisible files.
$delete = is_writable($file) ? "<a class=\"unlink\" href=\"{$script}?path={$path}&unlink={$file}\">delete</a>" : '';
echo '<li>' . $file . " $delete</li>";
}
echo "</ul>";
1) Try use this function to delete folder recursively (see manual, User contributed notes section http://php.net/manual/en/function.rmdir.php):
function delTree($dir) {
$files = array_diff(scandir($dir), array('.','..'));
foreach ($files as $file) {
(is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
}
return rmdir($dir);
}
2) Better develop some filemanager to allow users browse certain folders. Or see some ready solutions: http://www.jquery4u.com/plugins/10-jquery-file-manager-plugins/
I have a folder that contains logos for sponsors. In my website, a user can belong to a sponsor and the sponsor_id is set in session when the user logs in.
Here is my code:
function sponsor_logos($sponsor_id) {
$logos = glob("resources/content/sites/{$sponsor_id}*");
foreach($logos as $logo) {
if(file_exists("{$logo}"))
echo "<img src='/{$logo}' />";
}
}
The above works, but a sponsor can have multiple logos. So the multiple logos are saved like so: sponsor_id.jpg, sponsor_id_2.jpg, sponsor_id_3.jpg
I am not the strongest at regex, so any help is greatly appreciated! thanks!
You better open directory and check all files in it (if there are not so much files). You could do it like that:
function sponsor_logos($sponsor_id) {
if ($dh = opendir('resources/content/sites/')) {
while (($file = readdir($dh)) !== false) {
if(strpos($file, $sponsor_id . '.') === 0) {
$sponsor_files[] = $file;
}
else if(strpos($file, $sponsor_id . '_') === 0) {
$sponsor_files[] = $file;
}
}
closedir($dh);
}
foreach($sponsor_files as $logo) {
echo "<img src='resources/content/sites/" . $logo . "' />";
}
}
But best solution is to have normal naming scheme.
use this regex sponsor_id(_\d+)?\.jpg
I used the following code to display the contents of a Folder say images (Both Directories as well as Files in that folder)
<?php
$dir="images/"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
$newvar1="$dir$filename";// For Hyperlink Path
?>
<p><a href="<?php echo $newvar1; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
But the PHP file shows an output with two additional Links
A link to the folder 'images' and
A Link to the 'Homepage'.
I tried to filter those two links with "filesize" function but getting some error.
How can I resolve this?
Skip current dir and parent dir with a check.
while(...) {
if($filename == ".." || $filename == ".") continue;
...
}
Modify your code to something like this:
while(($filename = readdir($dir_list)) !== false)
{
if($filename != '.' || $filename != '..') // This part to check and ignore
$newvar1="$dir$filename";// For Hyperlink Path
else
continue; //while loop will no further be processed!
//...
}
This is a more in-depth answer and I'm so fed up with such things... This is absolutely an horrible piece of code, even though Php does permit such horrible things.
Something like this is easier to read, easier to maintain, and easier to debug:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
if($filename != ".." && $filename != ".")
{
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink)
{
echo '<p>'.$filename.'</p>';
}
?>
More compact but a bit less easy to read:
<?php
$tab = array();
$dir="images/"; // Directory to parse
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false) {
if($filename != ".." && $filename != ".") {
$tab[$filename] = $dir.$filename; // Hyperlink Path
}
}
closedir($dir_list);
}
/* Display separated from logic */
foreach ($tab as $filename => $hyperlink) {
echo '<p>'.$filename.'</p>';
}
?>
And some people (including my old teachers) tell that "if there's one line of code, don't use {}" (which I strongly disagree because it may lead to errors later on) but here's the "optimized" version:
<?php
$tab = array();
$dir="images/";
if ($dir_list = opendir($dir)) {
while(($filename = readdir($dir_list)) !== false)
if($filename != ".." && $filename != ".")
$tab[$filename] = $dir.$filename; // Hyperlink Path
closedir($dir_list);
}
foreach ($tab as $filename => $hyperlink)
echo '<p>'.$filename.'</p>';
?>