advice on building php based file manager - php

I am trying to build a php based file management system, but am having a few problems, basically I have found a script but it has problems reading directory names with spaces in them, here is the script :
<?php
global $dir_path;
if (isset($_GET["directory"])) {
$dir_path = $_GET["directory"];
//echo $dir_path;
}
else {
$dir_path = $_SERVER["DOCUMENT_ROOT"]."/";
}
$directories = scandir($dir_path);
foreach($directories as $entry) {
if (is_dir($dir_path . "/" . $entry) && !in_array($entry, array('.','..'))) {
echo "<li>" . $entry . "</li>";
}
else {}
}
?>
Any help would be greatly appreciated, thanks!

Related

PHP search with multiple hits

This is file1.php:
<?php
// Start the session
session_start();
?>
<?php
$path_to_check = '';
$needle = $_POST['query'];
foreach(glob($path_to_check . '*.xml') as $filename)
{
foreach(file($filename)as $fl)
{
if(strpos($fl, $needle)!==false)
{
$_SESSION["hit"] = $filename;
}
}
}
header('Location: file2.php');
?>
The search is working and returning the name of the file where searchword is found as a variable $_SESSION["hit"] = $filename;
However if the searchword is found in multiple files it will not work. Then I would need to go to another page file1b.php (or file1b.html) where the multiple files will be listed. Then from there do a choice to get to file2.php.
How could it be done?
Make $_SESSION['hit'] an array of all the filenames with a match.
$_SESSION['hit'] = array();
foreach(glob($path_to_check . '*.xml') as $filename)
{
foreach(file($filename)as $fl)
{
if(strpos($fl, $needle)!==false)
{
$_SESSION["hit"][] = $filename;
break;
}
}
}
You can then print the filenames with a simple loop.
foreach ($_SESSION['hit'] as $filename) {
echo $filename . "<br>";
}

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

PHP - displaying just PHP files from a directory and sub directories

This is my first project using PHP and I've been stuck on this for almost 2 days now!
I want to get all my PHP files from a directory and any sub directories and display them in iframes.
I've managed to get it to display all the files in the directory, but I only want the PHP files, please see below. Thanks in advance for any help/advice.
<?php
$path[] = 'work/*';
while(count($path) != 0)
{
$v = array_shift($path);
foreach(glob($v) as $item)
{
if (is_dir($item))
$path[] = $item . '/*';
elseif (is_file($item))
{
printf(
"<iframe width=420 height=150 frameborder=0 src='$item'></iframe>",
($file),$target);
}
}
}
?>
Change your glob pattern from work/* to work/*.php.
Change:
elseif (is_file($item))
To
elseif (is_file($item) && substr($item, -4) == '.php')
You can also use PHP's directory iterators, but the above is all you really need to do to get it working.
Eh, for fun, here's the iterator approach:
$dir = new RecursiveDirectoryIterator('work');
$iter = new RecursiveIteratorIterator($dir);
$regex = new RegexIterator($iter, '/^.+\.php$/');
foreach($regex as $filename)
{
// do something with $filename
}
Simple...replace $path[] = 'work/*'; with $path[] = 'work/*.php';
You're already using glob, this is the simplest way.
You should have better code :)
I specially did not add iframe so you can edit it by yourself to get a bit more experience :)
<?php
$iterator = new RecursiveDirectoryIterator('work/');
$files_count = 0;
foreach( new RecursiveIteratorIterator($iterator) as $filename => $cur) {
$file_info = pathinfo($filename);
if($file_info['extension'] === 'php') {
$files_count++;
echo $filename . "<br />";
}
}
echo "Total: $files_count files<br />";
?>

problem calling a php method from within itself

class styleFinder{
function styleFinder(){
}
function getFilesNFolders($folder){
$this->folder = $folder ;
if($this->folder==""){
$this->folder = '.';
}
if ($handle = opendir($this->folder)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file<br /> ";
if(is_dir($file)){
echo "<b>" . $file . " is a folder</b><br /> with contents ";
$this::getFilesNFolders($file);
# echo "Found folder";
}
}
}
closedir($handle);
}
}
}
I wan to print out a complete tree of folders and files, the script is going into the first folders and finding the files, then finding any sub folders, but not subfolders of those (and yes there is some). Any ideas please?
$this::getFilesNFolders($file);
Should Be
$this->getFilesNFolders($file);
Since PHP 5.1.2 you have this usefull class available: http://www.php.net/manual/en/class.recursivedirectoryiterator.php
Accessing a class function is done like this:
$this->functionName():
Since no one provided that yet, here is the RecursiveDirectoryIterator version of your code:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/directory'),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $fileObject) {
if($fileObject->isDir()) {
echo "<strong>$fileObject is a folder:</strong><br>\n";
} else {
echo $fileObject, "<br>\n";
}
}
As others have said, within the method itself, you need to call getFilesNFolders with $this -> getFilesNFolders($file). Also, the way the code is posted you're missing a } at the end, but since there is one starting the text after the code, that is probably a typo. The code below worked for me (I ran via the command line, so added code to indent different directory levels and also to output \n's):
<?php
class StyleFinder{
function StyleFinder(){
}
function getFilesNFolders($folder, $spaces){
$this->folder = $folder ;
if($this->folder==""){
$this->folder = '.';
}
if ($handle = opendir($this->folder)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($file)){
echo $spaces . "<b>" . $file . " is a folder</b><br/> with contents:\n";
$this -> getFilesNFolders($file, $spaces . " ");
} else {
echo $spaces . "$file<br />\n";
}
}
}
closedir($handle);
}
}
}
$sf = new StyleFinder();
$sf -> getFilesNFolders(".", "");
?>

Categories