show file list in folder from using browser - php

Normally if there is no htacces restriction is enabled it is possible to view the list of files under a folder hosted in web server using browsers. Except if there exist a index file like index.php it automatically go to the index page. (as far i know)
But is it possible to see the list of files though there exist an index file ?
thanks in advance

No, there is not. All web servers I'm aware of will only ever display a directory listing if there is no index page available (and, even then, only if directory listings are not disabled).

Build a file listing in PHP and display it in the index file.

Check out the info at http://php.net/manual/en/function.readdir.php . I used this for a client to display certain file types in a directory through the index.php file.
<?php
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
closedir($handle);
}
?>

Put this in the web root directory a sindex.php
<?php
$pngFolder = <<< EOFILE
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAA3NCSVQICAjb4U/gAAABhlBMVEX//v7//v3///7//fr//fj+/v3//fb+/fT+/Pf//PX+/Pb+/PP+/PL+/PH+/PD+++/+++7++u/9+vL9+vH79+r79+n79uj89tj89Nf889D88sj78sz78sr58N3u7u7u7ev777j67bL67Kv46sHt6uP26cns6d356aP56aD56Jv45pT45pP45ZD45I324av344r344T14J734oT34YD13pD24Hv03af13pP233X025303JL23nX23nHz2pX23Gvn2a7122fz2I3122T12mLz14Xv1JPy1YD12Vz02Fvy1H7v04T011Py03j011b01k7v0n/x0nHz1Ejv0Hnuz3Xx0Gvz00buzofz00Pxz2juz3Hy0TrmznzmzoHy0Djqy2vtymnxzS3xzi/kyG3jyG7wyyXkwJjpwHLiw2Liw2HhwmDdvlXevVPduVThsX7btDrbsj/gq3DbsDzbrT7brDvaqzjapjrbpTraojnboTrbmzrbmjrbl0Tbljrakz3ajzzZjTfZijLZiTJdVmhqAAAAgnRSTlP///////////////////////////////////////8A////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////9XzUpQAAAAlwSFlzAAALEgAACxIB0t1+/AAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAACqSURBVBiVY5BDAwxECGRlpgNBtpoKCMjLM8jnsYKASFJycnJ0tD1QRT6HromhHj8YMOcABYqEzc3d4uO9vIKCIkULgQIlYq5haao8YMBUDBQoZWIBAnFtAwsHD4kyoEA5l5SCkqa+qZ27X7hkBVCgUkhRXcvI2sk3MCpRugooUCOooWNs4+wdGpuQIlMDFKiWNbO0dXTx9AwICVGuBQqkFtQ1wEB9LhGeAwDSdzMEmZfC0wAAAABJRU5ErkJggg==
EOFILE;
if (isset($_GET['img']))
{
header("Content-type: image/png");
echo base64_decode($pngFolder);
exit();
}
$projectsListIgnore = array ('.','..');
$handle=opendir(".");
$projectContents = '';
while ($file = readdir($handle))
{
if (is_dir($file) && !in_array($file,$projectsListIgnore))
{
$projectContents .= '<li>'.$file.'</li>';
}
}
closedir($handle);
?>
<ul class="projects">
<?php $projectContents ?>
</ul>

Related

PHP - Scan dir for folders and txt

I am dynamically building an accordion menu. Accordion will get the header information from folder names and contents from .txt files associated to folder names. They are relatives in terms of directory.
<div class="accordion">
<?php if($_GET['cat']!='') {
$handleCat = 'tv/'.$_GET['cat'];
$category = scandir($handleCat);
$i = 1;
foreach ($category as &$value) {if ((!in_array($value,array(".","..","...")))){
echo '<div class="header">'.$value.'</div><div class="content" id="ac'.$i.'">'.file_get_contents($value.".txt", false).'</div>';
$i+=1;}}}
?>
</div>
In my code there are two problems. First one is logic problem. I couldn't made up scan foldernames and file names seperately. Forexample program1.txt also becomes a headername. Second problem is method problem. I found file_get_contents() method but this doesn't extracts .txt file contents.
You can distinguish files from folders using the function is_dir().
As of file_get_contents, it reads the file contents but does not echo it. Use :
echo '<div class="header">'.$value.'</div>'.$value.'<div class="content" id="ac'.$i.'">';
echo file_get_contents($value.".txt", false);
echo'</div>';
Use the following to list files in a directory. Where I commented code you can do whatever you want with that particular file. You can use is_dir() to distinguish from files and directories and then proceed accordingly.
<?php
if ($dir = opendir('.')) {
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
echo "$file\n";
//code
}
}
closedir($handle);
}
?>
Read the contents of a file using the following code.
$contents = file_get_contents($file);

PHP - Recursive - Open URL Using Variable Created From Sub Directory Names

I'm trying to write some PHP that runs through a folder grabbing each sub directory name and assigning it to a variable. Then, open a URL with that variable.
For example, D:Folder contains a number of sub folders named 1-??.
The PHP would first open www.url.com/run_batch.php?q=1 and sleep for 30 seconds, then www.url.com/run_batch.php?q=2, etc... for each sub directory in the main directory.
I'm currently in the process of trying to write this. I don't have much code yet, but thought one of you geniuses could help me speed up this process.
UPDATED
Ok, here is what I have so far, it runs without any errors, but it appears to be running all of them at once without sleeping? Not sure, the page just stays busy.
<?php
if ($handle = opendir('D:\HTTP\pic\')) {
$blacklist = array('.', '..', 'bu');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "<iframe width='800' height='600' src='http://www.url.com/run_batch.php?q=" . "$file" . "'></iframe>";
sleep(100);
}
}
closedir($handle);
}
?>
When you make a sleep in PHP code, the HTML is not sent to the browser, that is why it looks busy.
You have to call flush() on each pass.
<?php
if ($handle = opendir('D:\HTTP\pic\')) {
$blacklist = array('.', '..', 'bu');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "<iframe width='800' height='600' src='http://www.url.com/run_batch.php?q=" . "$file" . "'></iframe>";
//Send content to browser
flush();
sleep(100);
}
}
closedir($handle);
}
?>
I suggest you start with pseudo code; create comments for the steps. From there, look at PHP.net for help with specific tasks. When you have something workable but buggy, paste your code.
Pseudocode:
// get directory list
// loop through directories
// ...
// redirect to next page

get all file names from a directory in php

(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}

php directory explorer script help

I have created this php script which displays the contents of a designated directory and allows users to download each file. Here is the code:
<?php
if ($handle = opendir('test')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "<a href='test/$file'>$file\n</a><br/>";
}
}
closedir($handle);
}
?>
This script also displays folders, but when I click a folder, it does display the contents of the folder, but in the default Apache autoindex view.
What I would like the script to do when a folder is clicked, is display the contents, but in the same fashion as the original script does (as this is more editable with css and the like).
Would you know how to achieve this?
Don't create a link to the directory itself, but to a php page which displays the contents.
Change your php code to somthing like:
if(isset($_REQUEST['dir'])) {
$current_dir = $_REQUEST['dir'];
} else {
$current_dir = 'test';
}
if ($handle = opendir($current_dir)) {
while (false !== ($file_or_dir = readdir($handle))) {
if(in_array($file_or_dir, array('.', '..'))) continue;
$path = $current_dir.'/'.$file_or_dir;
if(is_file($path)) {
echo ''.$file_or_dir."\n<br/>";
} else {
echo ''.$file_or_dir."\n<br/>";
}
}
closedir($handle);
}
PS write you html code with double quotes.
You need your HREF to point back to your PHP script, and not the directory. You will then need to update your PHP script to now which directory it needs to read.

PHP Directory Listing Code Malfunction

I tried to write a script to list all files in directories and subdirectories and so on.. The script works fine if I don't include the check to see whether any of the files are directories. The code doesn't generate errors but it generates a hundred lines of text saying "Directory Listing of ." instead of what I was expecting. Any idea why this isn't working?
<?php
//define the path as relative
$path = "./";
function listagain($pth)
{
//using the opendir function
$dir_handle = #opendir($pth) or die("Unable to open $pth");
echo "Directory Listing of $pth<br/>";
//running the while loop
while ($file = readdir($dir_handle))
{
//check whether file is directory
if(is_dir($file))
{
//if it is, generate it's list of files
listagain($file);
}
else
{
if($file!="." && $file!="..")
echo "<a href='$file'>$file</a><br/>";
}
}
//closing the directory
closedir($dir_handle);
}
listagain($path)
?>
The first enties . and .. refer to the current and parent directory respectivly. So you get a infinite recursion.
You should first check for that before checking the file type:
if ($file!="." && $file!="..") {
if (is_dir($file)) {
listagain($file);
} else {
echo ''.htmlspecialchars($file).'<br/>';
}
}
The problem is, variable $file contains only basename of path. So, you need to use $pth.$file.

Categories