Page 1 of 1

Directory Listing File upload and create directory

Posted: Wed Apr 23, 2008 5:31 am
by amithanands
Hi i am developing a web site and in this web site i have to develop a page where i can list the directory files have an upload file option and create directory and the create sub directory to upload files

I am using 2 files

index.php

Code: Select all

<?
$startdir = '.';
$showthumbnails = true; 
$showdirs = true;
$forcedownloads = true;
$hide = array(
                '/intraweb/images',
                'index.php',
                'crdir.php',
                '.htaccess',
                '.htpasswd'
            );
$displayindex = false;
$allowuploads = true;
$overwrite = false;
$indexfiles = array (
                'index.html',
                'index.htm',
                'default.htm',
                'default.html'
            );
$filetypes = array (
                'png' => 'jpg.gif',
                'jpeg' => 'jpg.gif',
                'bmp' => 'jpg.gif',
                'jpg' => 'jpg.gif', 
                'gif' => 'gif.gif',
                'zip' => 'archive.png',
                'rar' => 'archive.png',
                'exe' => 'exe.gif',
                'setup' => 'setup.gif',
                'txt' => 'text.png',
                'htm' => 'html.gif',
                'html' => 'html.gif',
                'fla' => 'fla.gif',
                'swf' => 'swf.gif',
                'xls' => 'xls.gif',
                'doc' => 'doc.gif',
                'sig' => 'sig.gif',
                'fh10' => 'fh10.gif',
                'pdf' => 'pdf.gif',
                'psd' => 'psd.gif',
                'rm' => 'real.gif',
                'mpg' => 'video.gif',
                'mpeg' => 'video.gif',
                'mov' => 'video2.gif',
                'avi' => 'video.gif',
                'eps' => 'eps.gif',
                'gz' => 'archive.png',
                'asc' => 'sig.gif',
            );
error_reporting(0);
if(!function_exists('imagecreatetruecolor')) $showthumbnails = false;
$leadon = $startdir;
if($leadon=='.') $leadon = '';
if((substr($leadon, -1, 1)!='/') && $leadon!='') $leadon = $leadon . '/';
$startdir = $leadon;
if($_GET['dir']) {
    //check this is okay.
    if(substr($_GET['dir'], -1, 1)!='/') {
        $_GET['dir'] = $_GET['dir'] . '/';
    }
    $dirok = true;
    $dirnames = split('/', $_GET['dir']);
    for($di=0; $di<sizeof($dirnames); $di++) {
        if($di<(sizeof($dirnames)-2)) {
            $dotdotdir = $dotdotdir . $dirnames[$di] . '/';
        }
        if($dirnames[$di] == '..') {
            $dirok = false;
        }
    }
    if(substr($_GET['dir'], 0, 1)=='/') {
        $dirok = false;
    }
    if($dirok) {
         $leadon = $leadon . $_GET['dir'];
    }
}
 
if($_GET['download'] && $forcedownloads) {
    $file = str_replace('/', '', $_GET['download']);
    $file = str_replace('..', '', $file);
 
    if(file_exists($leadon . $file)) {
        header("Content-type: application/x-download");
        header("Content-Length: ".filesize($leadon . $file)); 
        header('Content-Disposition: attachment; filename="'.$file.'"');
        readfile($leadon . $file);
        die();
    }
}
 
if($allowuploads && $_FILES['file']) {
    $upload = true;
    if(!$overwrite) {
        if(file_exists($leadon.$_FILES['file']['name'])) {
            $upload = false;
        }
    }
    
    if($upload) {
        move_uploaded_file($_FILES['file']['tmp_name'], $leadon . $_FILES['file']['name']);
    }
}
 
$opendir = $leadon;
if(!$leadon) $opendir = '.';
if(!file_exists($opendir)) {
    $opendir = '.';
    $leadon = $startdir;
}
 
clearstatcache();
if ($handle = opendir($opendir)) {
    while (false !== ($file = readdir($handle))) { 
        //first see if this file is required in the listing
        if ($file == "." || $file == "..")  continue;
        $discard = false;
        for($hi=0;$hi<sizeof($hide);$hi++) {
            if(strpos($file, $hide[$hi])!==false) {
                $discard = true;
            }
        }
        
        if($discard) continue;
        if (@filetype($leadon.$file) == "dir") {
            if(!$showdirs) continue;
        
            $n++;
            if($_GET['sort']=="date") {
                $key = @filemtime($leadon.$file) . ".$n";
            }
            else {
                $key = $n;
            }
            $dirs[$key] = $file . "/";
        }
        else {
            $n++;
            if($_GET['sort']=="date") {
                $key = @filemtime($leadon.$file) . ".$n";
            }
            elseif($_GET['sort']=="size") {
                $key = @filesize($leadon.$file) . ".$n";
            }
            else {
                $key = $n;
            }
            $files[$key] = $file;
            
            if($displayindex) {
                if(in_array(strtolower($file), $indexfiles)) {
                    header("Location: $file");
                    die();
                }
            }
        }
    }
    closedir($handle); 
}
 
//sort our files
if($_GET['sort']=="date") {
    @ksort($dirs, SORT_NUMERIC);
    @ksort($files, SORT_NUMERIC);
}
elseif($_GET['sort']=="size") {
    @natcasesort($dirs); 
    @ksort($files, SORT_NUMERIC);
}
else {
    @natcasesort($dirs); 
    @natcasesort($files);
}
 
//order correctly
if($_GET['order']=="desc" && $_GET['sort']!="size") {$dirs = @array_reverse($dirs);}
if($_GET['order']=="desc") {$files = @array_reverse($files);}
$dirs = @array_values($dirs); $files = @array_values($files);
 
 
?>
<html>
<head>
    <SCRIPT language=Javascript>
        var text = "technologies.... "
            var speed = 100
            var x = 0
            function mks_statusbar() 
            {
                var a = text.substring(0,x)
                var b = text.substring(x,x+1).toUpperCase()
                var c = text.substring(x+1,text.length)
                window.status = a + b + c
                if (x == text.length) { x = 0 }
                else { x++ }
                setTimeout("mks_statusbar()",speed)
            }
        mks_statusbar   ();
    </SCRIPT>       
    <meta name="description" content="Technologies Private Ltd. - , India">
    <meta name="keywords" content="DSL, wireless, hardware virtualization, , India, broadband, ADSL">
    <link href="/intraweb/styles/global.css" rel="stylesheet" type="text/css">
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Directory Listing of <?=dirname($_SERVER['PHP_SELF']).'/'.$leadon;?></title>
    <link rel="stylesheet" type="text/css" href="/intraweb/images/styles.css" />
    
</head>
<body>
    <table align="center" class="maintable" width="815" cellspacing="10">
    <tr > <td colspan="2" >
        <table align="center" width="100%">
        <tr>  <td width="50%" align="left"><a href="http://www..com"><img src="/intraweb/images_new/logo_web_70.jpg" width="260" height="70" border="0"></a></td></tr>
        </table></td></tr>
    <tr><td colspan="2" class="banner"><img src="/intraweb/images_new/banner.jpg" width="800" height="70"></td></tr>
    <tr><td width="181" align="left" valign="top" class="sidemenu"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="175" height="300">
        <param name="movie" value="/intraweb/flash/xml_menu_engineering_documents_doc.swf">
        <param name="quality" value="high">
        <embed src="/intraweb/flash/xml_menu_engineering_documents_doc.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="175" height="300">
</embed></object><script type="text/javascript" src="/intraweb/jscript/iefix.js"></script></td>
        <td width="607" class="bodytable">
<?
if($showthumbnails) {
?>
<script language="javascript" type="text/javascript">
<!--
function o(n, i) {
    document.images['thumb'+n].src = '/intraweb/images/i.php?f='+i;
 
}
 
function f(n) {
    document.images['thumb'+n].src = '/intraweb/images/trans.gif';
}
//-->
</script>
<?
}
?>
</head>
<body>
<div id="container">
  <h1>Directory Listing of <?=dirname($_SERVER['PHP_SELF']).'/'.$leadon;?></h1>
  <div id="breadcrumbs"> <a href="<?=$_SERVER['PHP_SELF'];?>">home</a> 
  <?
     $breadcrumbs = split('/', $leadon);
    if(($bsize = sizeof($breadcrumbs))>0) {
        $sofar = '';
        for($bi=0;$bi<($bsize-1);$bi++) {
            $sofar = $sofar . $breadcrumbs[$bi] . '/';
            echo ' > <a href="'.$_SERVER['PHP_SELF'].'?dir='.urlencode($sofar).'">'.$breadcrumbs[$bi].'</a>';
        }
    }
  
    $baseurl = $_SERVER['PHP_SELF'] . '?dir='.$_GET['dir'] . '&';
    $fileurl = 'sort=name&order=asc';
    $sizeurl = 'sort=size&order=asc';
    $dateurl = 'sort=date&order=asc';
    
    switch ($_GET['sort']) {
        case 'name':
            if($_GET['order']=='asc') $fileurl = 'sort=name&order=desc';
            break;
        case 'size':
            if($_GET['order']=='asc') $sizeurl = 'sort=size&order=desc';
            break;
            
        case 'date':
            if($_GET['order']=='asc') $dateurl = 'sort=date&order=desc';
            break;  
        default:
            $fileurl = 'sort=name&order=desc';
            break;
    }
  ?>
  </div>
  <div id="listingcontainer">
    <div id="listingheader"> 
    <div id="headerfile"><a href="<?=$baseurl . $fileurl;?>">File</a></div>
    <div id="headersize"><a href="<?=$baseurl . $sizeurl;?>">Size</a></div>
    <div id="headermodified"><a href="<?=$baseurl . $dateurl;?>">Last Modified</a></div>
    </div>
    <div id="listing">
    <?
    $class = 'b';
    if($dirok) {
    ?>
    <div><a href="<?=$_SERVER['PHP_SELF'].'?dir='.urlencode($dotdotdir);?>" class="<?=$class;?>"><img src="/intraweb/images/dirup.png" alt="Folder" /><strong>..</strong> <em>-</em> <?=date ("M d Y h:i:s A", filemtime($dotdotdir));?></a></div>
    <?
        if($class=='b') $class='w';
        else $class = 'b';
    }
    $arsize = sizeof($dirs);
    for($i=0;$i<$arsize;$i++) {
    ?>
    <div><a href="<?=$_SERVER['PHP_SELF'].'?dir='.urlencode($leadon.$dirs[$i]);?>" class="<?=$class;?>"><img src="/intraweb/images/folder.png" alt="<?=$dirs[$i];?>" /><strong><?=$dirs[$i];?></strong> <em>-</em> <?=date ("M d Y h:i:s A", filemtime($leadon.$dirs[$i]));?></a></div>
    <?
        if($class=='b') $class='w';
        else $class = 'b';  
    }
    
    $arsize = sizeof($files);
    for($i=0;$i<$arsize;$i++) {
        $icon = 'unknown.png';
        $ext = strtolower(substr($files[$i], strrpos($files[$i], '.')+1));
        $supportedimages = array('gif', 'png', 'jpeg', 'jpg');
        $thumb = '';
        
        if($showthumbnails && in_array($ext, $supportedimages)) {
            $thumb = '<span><img src="/intraweb/images/trans.gif" alt="'.$files[$i].'" name="thumb'.$i.'" /></span>';
            $thumb2 = ' onmouseover="o('.$i.', \''.urlencode($leadon . $files[$i]).'\');" onmouseout="f('.$i.');"';
            
        }
        
        if($filetypes[$ext]) {
            $icon = $filetypes[$ext];
        }
        
        $filename = $files[$i];
        if(strlen($filename)>43) {
            $filename = substr($files[$i], 0, 40) . '...';
        }
        
        $fileurl = $leadon . $files[$i];
        if($forcedownloads) {
            $fileurl = $_SESSION['PHP_SELF'] . '?dir=' . urlencode($leadon) . '&download=' . urlencode($files[$i]);
        }
 
    ?>
    <div><a href="<?=$fileurl;?>" class="<?=$class;?>"<?=$thumb2;?>><img src="/intraweb/images/<?=$icon;?>" alt="<?=$files[$i];?>" /><strong><?=$filename;?></strong> <em><?=round(filesize($leadon.$files[$i])/1024);?>KB</em> <?=date ("M d Y h:i:s A", filemtime($leadon.$files[$i]));?><?=$thumb;?></a></div>
    <?
        if($class=='b') $class='w';
        else $class = 'b';  
    }   
    ?></div>
    <?
    if($allowuploads) {
        $phpallowuploads = (bool) ini_get('file_uploads');      
        $phpmaxsize = ini_get('upload_max_filesize');
        $phpmaxsize = trim($phpmaxsize);
        $last = strtolower($phpmaxsize{strlen($phpmaxsize)-1});
        switch($last) {
            case 'g':
                $phpmaxsize *= 1024;
            case 'm':
                $phpmaxsize *= 1024;
        }
    
    ?>
    <div id="upload">
        <div id="uploadtitle"><strong>File Upload</strong> (Max Filesize: 5 Mb<?//=$phpmaxsize;?>)</div>
        <div id="uploadcontent">
            <?
            if($phpallowuploads) {
            ?>
            <form method="post" action="<?=$_SERVER['PHP_SELF'];?>?dir=<?=urlencode($leadon);?>" enctype="multipart/form-data">
            <input type="file" name="file" /> <input type="submit" value="Upload" />
            </form>
            <?
            }
            else {
            ?>
            File uploads are disabled in your php.ini file. Please enable them.
            <?
            }
            ?>
        </div>
        
    </div>
    <div id="upload">
      <div id="uploadtitle"><strong>Create Directory</strong> </div>
      <div id="uploadcontent">
         <?
         if($phpallowuploads) {
         ?>
            <form action="crdir.php" method="post" enctype="multipart/form-data">
                <input type="text" name="dir" id="dir"/> <input type="submit" name="submit" value="Create Directory" />
            </form>
         <?
         }
         else {
         ?>
         File uploads are disabled in your php.ini file. Please enable them.
         <?
         }
         ?>
    </div>
      
   </div>
    <?
    }
    ?>
  </div>
</div>
 
 
</td></tr>
    <tr><td colspan="2" class="indexfooter">
    <table class="footerfont">
    <tr><td width="50%" align="left"> Copyright &copy;
                <script language="JavaScript">
                <!-- 
                var theYear; 
                today = new Date(); 
                theYear = today.getFullYear(); 
                document.write(theYear); 
                --> </script>
                 Technologies Pvt. Ltd. - , India
        </td><td width="50%" align="right">
        Site Design: <a href="http://www.blrbydesign.com/" target="_blank">BLR by design</a></td>
    </tr>
    </table>
    </td>
    </tr>
    </table>
 
<script language="JScript" type="text/jscript" src="/jscript/NoIEActivate.js"></script>
</body>
</html>
 
Next is crdir.php where from index.php u get the dir name and create it and copy the 2 files to the created directory and so on. . ]
 
crdir.php

Code: Select all

 
<?PHP
$dirname = $_POST['dir'];
//echo $dirname;
 
mkdir($dirname);
chmod ($dirname,0777);
 
$file1 = 'index.php';
$file2 = 'crdir.php';
 
$newfile2 = "$dirname/crdir.php";
copy($file2, $newfile2);    
chmod ($newfile3,0777);
 
$newfile1 = "$dirname/index.php";
copy($file1, $newfile1);    
chmod ($newfile1,0777);
 
header ("Location: ./");
//include "../`";
?>
 

1. is there any better way to create a directory which can be included in the index.php

2. if there is any... in this code of mine the subdirectories are created at one shot but for a second session its difficult to create inside a subdirectoey

Re: Directory Listing File upload and create directory

Posted: Wed Apr 23, 2008 5:33 am
by aceconcepts
Thats a lot of code and you haven't even used the code tags!!!