list directory in PHP hide extension - php

I have been searching for a way to hide an extension which appears from the directory list. I am showing these directory in a website menu but I would like all files to appear with their extension next to the file name. For example file.pdf and file.png.
I need to hide the extension from these files to appear as ( file , file , img , etc..).
php code:
<?php
$path = "./outgoing/";
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..')
printSubDir($file, $path, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
foreach ($queue as $file)
{
printFile($file, $path);
}
}
function printFile($file, $path)
{
echo "<li>$file</li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/",".pdf");
echo "</li>";
}
createDir($path);
?>

Use something like this to remove ext
$temp = explode(".", $file);
$par = $temp[0];

Related

PHP Directory, subdirectory and file Listing default sort order

i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);

Search for a folder and and get the content of the files inside

I'm trying to search for a folder and retrieve the files inside of the folder (get content) I'm able to search for the folder using the follow code but I can't pass from there I can't see the content an retrieve the files inside. The files inside will be txt files and I would like to be able to open and see then.
How can achieve what i want? Thank you.
<?php
$dirname = "C:\windows";//Directory to search in. *Must have a trailing slash*
$findme = $_POST["search"];
$dir = opendir($dirname);
while(false != ($file = readdir($dir))){//Loop for every item in the directory.
if(($file != ".") and ($file != "..") and ($file != ".DS_Store") and ($file !=
"search.php"))//Exclude these files from the search
{
$pos = stripos($file, $findme);
if ($pos !== false){
$thereisafile = true;//Tell the script something was found.
echo'' . $file . '<br>';
}else{
}
}
}
if (!isset($thereisafile)){
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
?>
New code
<?php
$dirname = "C:\\Windows\\";//Directory to search in. *Must have a trailing slash*
$findme = 'maxlink'; //$_POST["search"];
$files = scandir($dirname);
foreach ($files AS $file)
{
if ($file == '.' or $file == '..' or $file == '.DS_Store' or $file == 'search.php') continue;
if (stripos($file, $findme) !== false)
{
$found = true;
echo 'FOUND FILE ' . $file . '<hr>';
echo 'OPENING IT:<br>';
echo file_get_contents($dirname . $file);
echo '<hr>';
}
else
{
echo 'not found: ' . $file . '<br>';
}
}
if (!isset($found))
{
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
The following code uses a recursive function for searching the directory. I hope it’ll solve your problem.
function scandir_r($dir){
$files = array_diff(scandir($dir), array(".", ".."));
$arr = array();
foreach($files as $file){
$arr[] = $dir.DIRECTORY_SEPARATOR.$file;
if(is_dir($dir.DIRECTORY_SEPARATOR.$file)){
$arr = array_merge($arr, scandir_r($dir.DIRECTORY_SEPARATOR.$file));
}
}
return($arr);
}
$dirname = "C:\windows";
$findme = "/".preg_quote($_POST["search"], "/")."/";
$files = preg_grep($findme, scandir_r($dirname));
if(sizeof($files)){
foreach($files as $file){
$_file = $dirname.DIRECTORY_SEPARATOR.$file;
echo "$file<br/>";
}
}
else{
echo "Nothing was found.";
echo "<img src=\"yourimagehere.jpg\"/>";
}

Read file names from directory

I am trying to read and display all the files in a directory using this code.
It works fine for files in the same directory as the script. But when I try to display files in a folder (files/) it is giving me problems.
I've tried setting the directoy variable to many different things. like...
files/
files
/files/
etc... nothing seems to work. Does anyone have any idea why?
<?php
$dhandleFiles = opendir('files/');
$files = array();
if ($dhandleFiles) {
while (false !== ($fname = readdir($dhandleFiles))) {
if (is_file($fname) && ($fname != 'list.php') && ($fname != 'error.php') && ($fname != 'index.php')) {
$files[] = (is_dir("./$fname")) ? "{$fname}" : $fname;
}
}
closedir($dhandleFiles);
}
echo "Files";
echo "<ul>";
foreach ($files as $fname) {
echo "<li><a href='{$fname}'>{$fname}</a></li>";
}
echo "</ul>";
?>
You're not including the full path in your array:
while($fname = readdir($dhandleFiles)) {
$files[] = 'files/' . $fname;
^^^^^^^^---must include actual path
}
Remember that readdir() returns ONLY the filename, without path information.
This should help - take a look at SplFileInfo too.
<?php
class ExcludedFilesFilter extends FilterIterator {
protected
$excluded = array(
'list.php',
'error.php',
'index.php',
);
public function accept() {
$isFile = $this->current()->isFile();
$isExcluded = in_array($this->current(), $this->excluded);
return $isFile && ! $isExcluded;
}
}
$dir = new DirectoryIterator(realpath('.'));
foreach (new ExcludedFilesFilter($dir) as $file) {
printf("%s\n", $file->getRealpath());
}
How about using glob function.
<?php
define('MYBASEPATH' , 'files/');
foreach (glob(MYBASEPATH . '*.php') as $fname) {
if($fname != 'list.php' && $fname != 'error.php' && $fname != 'index.php') {
$files[] = $fname;
}
}
?>
read more about getting all files in directory here
This reads and prints filenames from a sub-directory:
$d = dir("myfiles");
while (false !== ($entry = $d->read())) {
if ($entry != ".") {
if ($entry != "..") {
print"$entry";
}
}
}
$d->close();

Control the order of the files with opendir() & readdir()

I checked at php.net opendir() but found no way to control the order of the files that opendir() gets.
I have a slideshow and I have problems controling the order of the images. I tried changing names and use 01.img,02.img,...,20.img but no sucess.
My script:
<?php
$path2 = "./img/";
function createDir($path2 = './img'){
if ($handle = opendir($path2)){
echo "<ul class=\"ad-thumb-list\">";
while (false !== ($file = readdir($handle))){
if (is_dir($path2.$file) && $file != '.' && $file !='..')
printSubDir($file, $path2, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path2);
echo "</ul>";
}
}
function printQueue($queue, $path2){
foreach ($queue as $file){
printFile($file, $path2);
}
}
function printFile($file, $path2){
if ($file=="thumbs.db") {echo "";}
else{
echo "<li><a href=\"".$path2.$file."\">";
echo "<img src=\"".$path2.$file."\" class='thumbnail'></a></li>";
}
}
/*function printSubDir($dir, $path2)
{
}*/
createDir($path2);
?>
Use scandir() and natsort().
Rewritten code:
function createDir($path2 = './img'){
$dirContents = scandir($path2);
natsort($dirContents);
echo "<ul class=\"ad-thumb-list\">";
// You should actually add the line below!
// $queue = array();
foreach ($dirContents as $entry) {
if ($entry == '.' || $entry == '..') {
continue;
}
$entryPath = $path2 . $entry;
if (is_dir($entryPath)) {
printSubDir($entry, $path2, $queue);
}
else {
$queue[] = $entry;
}
}
printQueue($queue, $path2);
echo "</ul>";
}
}
If you are using PHP 5, you could try using scandir() instead. It has an argument for sorting.
http://us1.php.net/scandir
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
As #Steven has already said, you may not be able to change the output of opendir(), but there's nothing stopping you from sorting the array afterwards.
To do this, have a look at the natsort() function, which is designed to properly sort strings like those you're using for file names.

Pull Images from directory - PHP

I am trying to pull images simply from my directory /img and load them dynamically into the website into the following fashion.
<img src="plates/photo1.jpg">
That's it. It seems so simple but all of the code I have found basically doesn't work.
What I have that I am trying to make work is this:
<?php
$a=array();
if ($handle = opendir('plates')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/\.png$/", $file))
$a[]=$file;
else if(preg_match("/\.jpg$/", $file))
$a[]=$file;
else if(preg_match("/\.jpeg$/", $file))
$a[]=$file;
}
closedir($handle);
}
foreach($a as $i){
echo "<img src='".$i."' />";
}
?>
This can be done very easily using glob().
$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
print "<img src=\"plates/$file\" />";
You want your source to show up as plates/photo1.jpg, but when you do echo "<img src='".$i."' />"; you are only writing the file name. Try changing it to this:
<?php
$a = array();
$dir = 'plates';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
You should use Glob instead of opendir/closedir. It's much simpler.
I'm not exactly sure what you're trying to do, but you this might get you on the right track
<?php
foreach (glob("/plates/*") as $filename) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == "png") {
// do something
} elseif($path_parts['extension'] == "jpg") {
// do something else
}
}
?>

Categories