Loop sub folders and make them dynamic links in php - php

I need help on this one
I have managed to loop through my parent folder and echo the sub folder en wants to create on PHP file that can help me loop through the sub folders. my code is below:
<?php
$path="../downloads/pastpapers/UCU/foundations/";
$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
$dirName=$fileinfo->getFilename();
echo "<div id='linkFrame'><a href='$dirName.php'><img src='images/folder.png'><br/>$dirName</img></a> </div>";
}
}
?>

Just try the following in test file php :
<?php
$path = '../downloads/pastpapers/UCU/foundations';
ListFolder($path);
function ListFolder($path)
{
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$explode = explode("/", $path);
$dirname = end($explode);
//display the target folder.
echo ("<li>$dirname\n");
echo "<ul>\n";
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
ListFolder($path."/".$file);
}
else
{
//Display a list of files.
echo "<li>$file</li>";
}
}
}
echo "</ul>\n";
echo "</li>\n";
//closing the directory
closedir($dir_handle);
}
?>
for more information pls visit this page

Related

If directory is not empty?

I have a slightly older, patched up PHP script that evaluates a directory and actually works great. But I would now have to integrate an error message in case the directory is empty. I had some ideas, but nothing worked. Does anyone know advice?
function the_downloads() {
function ListFolder($path, $depth=0)
{
// using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
// Leave only the lastest folder name
$inter = explode("/", $path); // using intermediate var to prevent warning in strict mode: http://stackoverflow.com/questions/2354609/strict-standards-only-variables-should-be-passed-by-reference
$dirname = end($inter);
if ($depth > 0) {
// display the target folder
echo str_repeat("\t", $depth) . "<li class='downloads__folder'><span class='downloads__folder__titel'>$dirname</span>\n";
}
echo str_repeat("\t", $depth) . "<ul class='downloads__folder__list'>\n";
while (false !== ($file = readdir($dir_handle))) {
// skip hidden files
if (preg_match('/^\./', $file)) {
continue;
}
$subdirs[] = $file;
}
natcasesort($subdirs);
foreach ($subdirs as $subdir) {
if (is_dir($path."/".$subdir)) {
// Display a list of sub folders.
ListFolder($path."/".$subdir, $depth+1);
}
else {
// Display a list of files.
echo str_repeat("\t", $depth+1) . "<li class=\"downloads__file\">$subdir</li>\n";
}
}
echo str_repeat("\t", $depth) . "</ul>\n";
// closing the directory
closedir($dir_handle);
}
ListFolder("wp-content/uploads/_downloads/composition");
}
You can use glob function to list files/directories inside folder:
https://www.php.net/manual/en/function.glob.php

How to presence of some string data in PHP code

I have the code below which list files from directory and all sub directory and its working fine.
Now what I want to achieve is to only display PHP files that contains the following string functions
eval, system, shell_exec.
I guess I have to create an array like
$check=array("unescape", "system(","shell_exec(");
Below is the code that just list all the PHP files
function c_check($path){
if(file_exists($path) && is_dir($path)){
$files = glob($path ."/*");
if(count($files) > 0){
// Loop through retuned array
foreach($files as $file){
if(is_file("$file")){
// Display only filename
echo basename($file) . "<br>";
} else if(is_dir("$file")){
c_check("$file");
}
}
} else{
echo " directory file not found";
}
} else {
echo " directory does not exist.";
}
}
// Call the function
c_check("../content_folder");
You could do something similar to the code below, loading each file and then checking if it contains any of those strings.
Keep in mind this won't be very fast, i'd consider using something like grep and parsing it's output.
function c_check($path)
{
$checks = ["unescape", "system(", "shell_exec("];
if (file_exists($path) && is_dir($path)) {
$files = glob($path . "/*");
if (count($files) > 0) {
// Loop through returned array
foreach ($files as $file) {
if (is_file("$file")) {
$fileContents = file_get_contents($file);
foreach ($checks as $illegalString) {
if (strpos($fileContents, $illegalString) !== false) {
echo basename($file) . "<br>";
}
}
} else {
if (is_dir("$file")) {
c_check("$file");
}
}
}
} else {
echo " directory file not found";
}
} else {
echo " directory does not exist.";
}
}
You have to read the content of the file first and do a search. Try replacing your if block in foreach loop with this.
if(is_file("$file")){
$contents = file_get_contents($file);
if(strpos($contents, "eval")!==false || strpos($contents, "system")!==false || strpos($contents, "shell_exec")!==false){
//this is the file you're looking for.
}
}
It read the content for the file and make a search for the words.

Create links from file name from folder

Iam writting here for the first time. I wrote some php code which read files from folder and makes list of links to each file. Problem is that, its generates two more links at the begining of the list, which arent links to files, only dots. Does anyone have some idea to help me about this? This is the code:
<?php
echo '<h1>Download</h1>';
echo '<br/>';
echo '<div id="download">';
$dir = "images/download/";
if (is_dir($dir)) {
if($dh = opendir($dir)) {
while(($file = readdir($dh))!==false){
echo ''. str_replace("_"," ", trim($file,'.pdf, .pptx')) . "";
}
closedir($dh);
}
}
echo '</div>';
?>
You always have to check for the . and .. directories and ignore them. They exist in every folder.
They are what are used when you do cd .. and ls . for example in a command window
<?php
echo '<h1>Download</h1>';
echo '<br/>';
echo '<div id="download">';
$dir = "images/download/";
if (is_dir($dir)) {
if($dh = opendir($dir)) {
while(($file = readdir($dh))!==false){
if ( $file == '.' || $file == '..' ) {
continue;
}
echo ''. str_replace("_"," ", trim($file,'.pdf, .pptx')) . "";
}
closedir($dh);
}
echo '</div>';
?>

php loop through files in subfolders in folder and get file paths

Im really new to PHP i searched google to find a correct script that loops through all subfolders in a folder and get all files path in that subfolder
<?php
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename. '<br/>';
}
?>
So i have folder 'posts' in which i have subfolder 'post001' in which i have two files
controls.png
text.txt
And the code above echos this
posts\.
posts\..
posts\post001\.
posts\post001\..
posts\post001\controls.png
posts\post001\text.txt
But i want to echo only the file paths inside these subfolders like this
posts\post001\controls.png
posts\post001\text.txt
The whole point of this is that i want to dynamically create divs for each subfolder and inside this div i put img with src and some h3 and p html tags with text equal to the .txt file so is this proper way of doing that and how to remake my php script so that i get just the file paths
So I can see the answers and they are all correct but now my point was that i need something like that
foreach( glob( 'posts/*/*' ) as $filePath ){
//create div with javascript
foreach( glob( 'posts/$filePath/*' ) as $file ){
//append img and h3 and p html tags to the div via javascript
}
//append the created div somewhere in the html again via javascript
}
So whats the correct syntax of doing these two foreach loops in php im really getting the basics now
See if this works :)
$di = new RecursiveDirectoryIterator('posts');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
if ((substr($file, -1) != '.') && (substr($file, -2) != '..')) {
echo $file . '<br/>';
}
}
<h1>Directory Listing</h1>
<?php
/**
* Recursive function to append the full path of all files in a
* given directory $dirpath to an array $context
*/
function getFilelist($dirpath, &$context){
$fileArray = scandir($dirpath);
if (count($fileArray) > 2) {
/* Remove the . (current directory) and .. (parent directory) */
array_shift($fileArray);
array_shift($fileArray);
foreach ($fileArray as $f) {
$full_path = $dirpath . DIRECTORY_SEPARATOR . $f;
/* If the file is a directory, call the function recursively */
if (is_dir($full_path)) {
getFilelist($full_path, $context);
} else {
/* else, append the full path of the file to the context array */
$context[] = $full_path;
}
}
}
}
/* $d is the root directory that you want to list */
$d = '/Users/Shared';
/* Allocate the array to store of file paths of all children */
$result = array();
getFilelist($d, $result);
$display_length = false;
if ($display_length) {
echo 'length = ' . count($result) . '<br>';
}
function FormatArrayAsUnorderedList($context) {
$ul = '<ul>';
foreach ($context as $c) {
$ul .= '<li>' . $c . '</li>';
}
$ul .= '</ul>';
return $ul;
}
$html_list = FormatArrayAsUnorderedList($result);
echo $html_list;
?>
Take a look at this:
<?php
$filename[] = 'posts\.';
$filename[] = 'posts\..';
$filename[] = 'posts\post001\.';
$filename[] = 'posts\post001\..';
$filename[] = 'posts\post001\controls.png';
$filename[] = 'posts\post001\text.txt';
foreach ($filename as $file) {
if (substr($file, -4, 1) === ".") {
echo $file."<br>";
}
}
?>
Result:
posts\post001\controls.png
posts\post001\text.txt
What this does is checking if the 4th last digit is a dot. If so, its an extension of three letters and it should be a file. You could also check for specific extensions.
$ext = substr($file, -4, 4);
if ($ext === ".gif" || $ext === ".jpg" || $ext === ".png" || $ext === ".txt") {
echo $file."<br>";
}

PHP nested file tree

I have searched on google and on this site for something similar to what I want but nothing fits exactly and all my efforts to adapt them have failed, I want to make a script that will map out its directory and all its subfolders and the folders be at the top of the subdirectory and files after them. So far I have come up with this:
<?php
$rawParent = scandir('.');
$parentDir = array_diff($rawParent, array('.', '..','cgi-bin','error_log'));
$arrayOfDirectories = array();
$arrayOfFiles = array();
foreach ($parentDir as $child){
if(is_dir($child)){
array_push($arrayOfDirectories,$child);
}else{
array_push($arrayOfFiles,$child);
}
}
foreach ($arrayOfDirectories as $directory){
echo $directory.'<br>';
}
echo "<br>";
foreach ($arrayOfFiles as $file){
echo "<a href='".$file."'>".$file.'</a><br>';
}
?>
It's good so far but it only does the first level of the directory, can this code be adapted to go through all levels of folders and nest them? If so how? I need a few pointers, I will further use javascript to have toggles on the folders to see the contents, so I will need PHP to output something nested.
Sorry if I am not making much sense, don't really know how to explain.
Use recursive function like this :
<?php
function list_directory($directory)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
print '<ul>'.$directory.'/'.$file;
list_directory($directory.'/'.$file);
print '</ul>';
}
else
{
print "<li> $file </li>";
}
}
closedir($the_directory);
}
$path_to_search = '/var/www';
list_directory($path_to_search);
?>
Version with storage in array :
<?php
function list_directory($directory, &$storage)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
list_directory($directory.'/'.$file, $storage);
}
else
{
$storage[] = $file;
}
}
closedir($the_directory);
}
$storage = array();
$path_to_search = '/var/www';
list_directory($path_to_search, $storage);
echo '<pre>', print_r($storage,true) , '</pre>';
?>
This will do what you asked for, it only returns the sub directory names in a given path, and you can make hyperlinks and use them.
$yourStartingPath = "your string path";
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($yourStartingPath),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$path = strtoupper($file->getRealpath()) ;
$path2 = PHP_EOL;
$path3 = $path.$path2;
$result = end(explode('/', $path3));
echo "<br />". basename($result);
}
}

Categories