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);
Related
I have a folder / directory containing lots of images and other folders / directories.
I am showing the preview of these files using following code:
<?php
$images=array();
$dir_handler = opendir('test') or die("Unable to open path");
$i=0;
while($file = readdir($dir_handler))
{
if(is_dir($file))
continue;
else if($file != '.' && $file != '..' && $file != 'index.php')
{
$images[$i]=$file;
$i++;
}
}
sort($images);
for($i=0; $i<sizeof($images); $i++)
{
echo "<img style='border:1px solid #666666; width:100px;height:100px; margin: 10px;' src='test/".$images[$i]."'/><input type='button' value='nok[]'>";
} closedir($dir);
?>
The problem is that I want to assign a separate button to each file (to each image or folder), So that by clicking each button, its corresponding image (or folder / directory) gets deleted from the main folder and no more being shown as a preview.
Another small problem is that the preview of folders are not being shown with the above code. Why? Any help will be appreciated.
There are several questions here.
First question: Why won't preview of folders show? This is because you show previews by looping through the $images array, but you do not add directories to that array (see your code where you check if it is_dir and then invoke "continue;"). If you want to include the directories, then you should include them in the $images array (or do something else with them).
Second question: How to do the deleting? You need to either extend your existing PHP script or write another one. You would create a link on the delete icon; the link's href would be to the new (or existing) PHP script and you would pass in as parameters the folder or file to be deleted. If it is a folder, then use rmdir(). If it is a file, then use unlink(). I can help you more with this later, if you need it.
You are always displaying an image, you need to do a check if the $images array value is an image or a folder. Then do something different with the display.
To delete a file or folder, use these functions respectively:
unlink();
rmdir();
http://www.php.net/manual/en/function.rmdir.php
http://php.net/manual/en/function.unlink.php
To add a list of folders before your images change your code to:
<?php
$images=array();
$folders = array();
$dir_handler = opendir('test') or die("Unable to open path");
$i=0;
while($file = readdir($dir_handler))
{
if(is_dir($file)) {
$folders[count($folders)] = $file;
}
else if($file != '.' && $file != '..' && $file != 'index.php')
{
$images[$i]=$file;
$i++;
}
}
sort($images);
foreach($folders as $folder){
echo "<a href='#'>$folder</a>";
}
for($i=0; $i<sizeof($images); $i++)
{
echo "<img style='border:1px solid #666666; width:100px;height:100px; margin: 10px;' src='test/".$images[$i]."'/><input type='button' value='nok[]'>";
}
closedir($dir);
?>
Then all you have to do is build out the visual elements of a folder in your view and link to a function that will do your unlink() and rmdir() where needed.
(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)
}
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>
I have the following PHP code to display the file structure of my site. This gives my a very nice indented structure with folder and file images.
How can I add JQuery to this so I can collapse and expand the folders? I tried a couple of jquery plugins but they didn't work.
Can you suggest a jquery plugin or an article or code snippet?
Thank you!
<?php
$path = ROOT_PATH;
$dir_handle = #opendir($path) or die("Unable to open $path");
list_dir($dir_handle,$path);
function list_dir($dir_handle,$path)
{
echo "<ul>";
while (false !== ($file = readdir($dir_handle)))
{
$dir =$path.'/'.$file;
if(is_dir($dir) && $file != '.' && $file !='..' )
{
$handle = #opendir($dir) or die("undable to open file $file");
echo '<li><input name="" type="image" src="themes/default/images/explore/folder.png" />'.$file.'</li>';
list_dir($handle, $dir);
}
elseif($file != '.' && $file !='..')
{
echo '<li><input name="" type="image" src="themes/default/images/explore/file.png" />'.$file.'</li>';
}
}
echo "</ul>";
closedir($dir_handle);
}
?>
With the structure you have, a nested <ul> tree, this should be relatively easy.
Your folders all have <li> elements with anchors in them, not quite sure why as you have input-images inside them which are clickable in their own right. Put a class on these anchors or the input called "folder" or somesuch. Then all you need to do is hide all the ULs to start with apart from the root folder and use jQuery to show/hide the nested <ul> lists when a user clicks on the associated folder.
Providing you setup that "folder" class, try the following code.
/* if you want to hide all but the root with code */
$('ul:gt(0)').hide();
$('.folder').click(function() {
$(this).parents('li:first').next('ul').slideToggle('slow');
return false;
});
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.