Foros del Web » Programando para Internet » PHP »

Script explorador de archivos

Estas en el tema de Script explorador de archivos en el foro de PHP en Foros del Web. Hola, lo primero felices fiestas a todos A ver si me podéis echar una mano tengo un script que sirve para explorar los archivos y ...
  #1 (permalink)  
Antiguo 22/12/2007, 07:10
 
Fecha de Ingreso: julio-2007
Mensajes: 75
Antigüedad: 16 años, 9 meses
Puntos: 0
Script explorador de archivos

Hola, lo primero felices fiestas a todos


A ver si me podéis echar una mano tengo un script que sirve para explorar los archivos y mostrar los ficheros (tamaño, fecha creación, fecha modificación, etc...), pero sólo quiero que me muestre de un directorio X y sus subdirectorios, con sus respectivos archivos, el script hace lo que quiero pero si le das a subir de nivel una vez estás en el directorio X, sigue subiendo y muestra todo mi árbol de directorios.....

Cómo podría solucionar esto?? Se os ocurre algo? Voy a poner el código del script a ver si me podéis ayudar, gracias a todos.


Un saludo

Código de script:


<?php
// ---- version number ----
define( 'VERSION_INFO', 'v1.2' );

function parse_tags($str) {
$trans = array( "&" => "&amp;", '"' => "&quot;", "<" => "&lt;", ">" => "&gt;" );

return strtr(stripslashes($str), $trans);
}
function download($file){

$ext = substr(strrchr(basename($file), "."), 1);//get the file ext

header("Content-type: application/$ext");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($file));
header("Content-disposition: attachment; filename=\"".basename($file)."\"");
readfile($file);
}

//the file download if user click on it.
$fname = trim($_GET['fname']);
//this will make sure the file exist
if( !empty($fname) && file_exists($fname) && @fopen($fname, "rb") ) {
download($fname);
}

//Execute only if user input some code, executing move to below
$script = trim($_POST['editor']);
if( !empty($script) ) {

//value to put it back to the editor
$display = "inherit";
$value = "&and;";
$editor = parse_tags($script);
}
else {
//close the editor
$display = "none";
$value = "&or;";
$editor = "";
}

$self = basename(__FILE__);

$get_dir = $_GET['dir'];
$home = str_replace( "\\", "/", dirname(__FILE__) );

//which folder to browse (failsafe)
if( !empty($_GET['dir']) && @opendir($get_dir) ) {
$dir = str_replace( "\\", "/", $get_dir );
}
else { //default dir
$dir = $home;
}

//the search criteria to obey
$fname = trim($_POST['fname']);
$content = trim($_POST['content']);

//its searching now, set the search box open
if( !empty($fname) || !empty($content) ) {
$display2 = "inherit";
$value2 = "&and;";

//value use to inherit back to the input
$fname_value = parse_tags($fname);
$content_value = parse_tags($content);

if($_POST['dir'] == 1) {
$subdirs = 1;
$check = " checked=\"checked\"";
}
else {
$subdirs = 0;
$check = "";
}
}
else {
$display2 = "none";
$value2 = "&or;";

//defaulr is checked
$check = " checked=\"checked\"";
}

// The main function of the program

function loop_dir($dir) {
global $self, $fname, $content, $subdirs, $refresh, $dir_up, $all_dir, $unread_dir, $all_file, $unread_file;

//check if directory can be open
if ($handle = @opendir($dir)) {

//loop through the dir for FILES and DIR
while ( false != ($file = readdir($handle)) ) {

//increase the maximum execute time
set_time_limit(10);
$full_path = str_replace( "//", "/", $dir . "/" . $file);

if( $file == "." ) {
$refresh = "<tr bgcolor=\"#F5F5F5\">
<td align=\"left\"><img src=\"./sysimg/refresh.png\" border=\"0\" alt=\"\" />
<a href=\"$self?dir=$dir\">Refresh</a></td>
<td align=\"center\"></td>
<td align=\"left\"></td>
<td align=\"left\"></td></tr>\r\n";
}
elseif( $file == ".." ) {
$up_lvl = str_replace( "\\", "/", dirname($dir . "..") );
$dir_up = "<tr bgcolor=\"#FFFFFF\">
<td align=\"left\"><img src=\"./sysimg/back.png\" border=\"0\" alt=\"\" />
<a href=\"$self?dir=$up_lvl\">Up one level</a></td>
<td align=\"center\"></td>
<td align=\"left\"></td>
<td align=\"left\"></td></tr>\r\n";
}
//this is a directory, set the attr etc.
elseif( is_dir($full_path) ) {

$perm = substr(sprintf('%o', @fileperms("$full_path")), -4);
$time_mod = date("Y M d h:i A" ,filemtime($full_path));

//check if the dir can be open or not
if( @opendir($full_path) ) {

//loop to subdirs if specify by user
if( $subdirs == 1 ) {
loop_dir($full_path);
}

if( !empty($fname) ) { //searching of folder

if( stristr($file, $fname) ) { //search for the dir

//store all dirs in array
$all_dir[] .= "<td align=\"left\"><img src=\"./ext_ico/folder.png\" border=\"0\" alt=\"\" />
<a href=\"$self?dir=$full_path\" title=\"$full_path\">" . $file . "</a></td>
<td align=\"center\">-</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}
elseif( stristr($file, $fname) ) { //search for the dir
//store all dirs in array
$all_dir[] .= "<td align=\"left\"><img src=\"./ext_ico/folder.png\" border=\"0\" alt=\"\" />
<a href=\"$self?dir=$full_path\" title=\"$full_path\">" . $file . "</a></td>
<td align=\"center\">-</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}
}
elseif( empty($content) ) { //not searching, display them all

//store all dirs in array
$all_dir[] .= "<td align=\"left\"><img src=\"./ext_ico/folder.png\" border=\"0\" alt=\"\" />
<a href=\"$self?dir=$full_path\" title=\"$full_path\">" . $file . "</a></td>
<td align=\"center\">-</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}

}
else { //the dir cannot be read
$unread_dir[] .= "<td align=\"left\"><img src=\"./ext_ico/folder2.png\" border=\"0\" alt=\"\" /> "
. $file . "</td>
<td align=\"center\">-</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}

}
else {
//for normal file, these are the attr
$size = filesize($full_path);

if( $size >= 0 && $size < 1024 ) {
$size = $size . " B";
}
elseif( $size >= 1024 && $size < 1048576 ) { //round to KB
$size = round(($size/1024),2) . " KB";
}
elseif( $size >= 1048576 && $size < 1073741824 ) { //round to MB
$size = round(($size/1048576),2) . " MB";
}
elseif( $size >= 1073741824 ) { //round to GB
$size = round(($size/1073741824),2) . " GB";
}
else { //invalid size, error
$size = "--";
}

$perm = substr(sprintf('%o', @fileperms("$full_path")), -4);
$time_mod = date("Y M d h:i A" ,filemtime($full_path));

//check for icon for this filetype
$ext = substr(strrchr($file, "."), 1);

//icon for normal readable file
if( file_exists( "./ext_ico/" . $ext . ".png") ) {
$icon_normal = "./ext_ico/" . $ext . ".png";
}
else { //set as unknown filetype icon
$icon_normal = "./ext_ico/file.png";
}

//icon for unreadable file
if( file_exists( "./ext_ico/" . $ext . "2.png") ) {
$icon_unview = "./ext_ico/" . $ext . "2.png";
}
else { //set as unknown filetype icon
$icon_unview = "./ext_ico/file2.png";
}

//check if the file can be read
if( @fopen($full_path, "rb") ) {

//search for the content as well if user request
if( !empty($content) ) {
$file_data = file_get_contents($full_path);
}

//searching for files and content if so
if( !empty($fname) ) {

//search for the name
if( stristr($file, $fname) ) {

//store all files in array
$all_file[] .= "\n<!--$file!-->
<td align=\"left\"><img src=\"$icon_normal\" border=\"0\" alt=\"\" />
<a href=\"$self?fname=$full_path\" title=\"$full_path\">" . $file . "</a></td>
<td align=\"right\">$size</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}
}
//search the file with part of this content
elseif( !empty($content) ) {

if( stristr($file_data, $content) ) {
//store all files in array
$all_file[] .= "\n<!--$file!-->
<td align=\"left\"><img src=\"$icon_normal\" border=\"0\" alt=\"\" />
<a href=\"$self?fname=$full_path\" title=\"$full_path\">" . $file . "</a></td>
<td align=\"right\">$size</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}

}
elseif( empty($fname) ) {

//store all files in array
$all_file[] .= "\n<!--$file!-->
<td align=\"left\"><img src=\"$icon_normal\" border=\"0\" alt=\"\" />
<a href=\"$self?fname=$full_path\" title=\"$full_path\">" . $file . "</a></td>
<td align=\"right\">$size</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}
}
else {
//file cannot be read
$unread_file[] .= "\n<!--$file!-->
<td align=\"left\"><img src=\"$icon_unview\" border=\"0\" alt=\"\" /> "
. $file . "</td>
<td align=\"right\">$size</td>
<td align=\"center\">$perm</td>
<td align=\"left\">$time_mod</td>";
}
}
//incre the file number
$file_count++;
}

//display the files and dirs
@natcasesort($all_dir);
@natcasesort($unread_dir);
@natcasesort($all_file);
@natcasesort($unread_file);
}
}
//End of main function

Os pongo la función principal del script sólamente, no me deja meter más caracteres.
  #2 (permalink)  
Antiguo 22/12/2007, 08:52
 
Fecha de Ingreso: agosto-2003
Ubicación: España
Mensajes: 202
Antigüedad: 20 años, 8 meses
Puntos: 0
Re: Script explorador de archivos

Lo adequado seria plantear lo que necesitas y programarlo tu misma, porque de esta forma es muy lioso y ayudarte es complicado, para escanear un directorio.

Resulta complicado entender esta funcion y mas si esta incompleta :S lo siento.
  #3 (permalink)  
Antiguo 22/12/2007, 10:52
 
Fecha de Ingreso: julio-2007
Mensajes: 75
Antigüedad: 16 años, 9 meses
Puntos: 0
Re: Script explorador de archivos

gracias por contestar ivanguillen... Lo que quiero hacer es lo siguiente:

Otros Directorios
Directorio X
SubdirectorioX.1
Fichero1
Fichero2
SubdirectorioX.2
Fichero1
Fichero2

SubdirectorioX.N
Fichero1
Fichero2


Imaginad que tengo esta estructura y quiero mostrar los ficheros y subdirectorios de X con valores de creación, modificación, tamaño, etc.....

Pero no quiero que se pueda ver lo que hay encima de Directorio X pero si que se muevan entre los SubdirectoriosX.1... SubdirectoriosX.N; no sé si me he explicado bien.
  #4 (permalink)  
Antiguo 22/12/2007, 11:16
 
Fecha de Ingreso: agosto-2003
Ubicación: España
Mensajes: 202
Antigüedad: 20 años, 8 meses
Puntos: 0
Re: Script explorador de archivos

Aha ;)
perfecto ahora lo entiendo, pues bien, aqui abajo te dejo una rutina que te permitira escanear un directorio y sus subdirectorios y mostrar los archivos y sus propiedades. Si le falta algo al script dimelo y me lo vuelvo a mirar ;)

Código:
function listar($ruta){
   if (is_dir($ruta)) {
      if ($dr = opendir($ruta)) {
         while (($file = readdir($dr)) !== false) {
            echo "<hr>Informacion del archivo:\n";
            echo "Nombre de archivo: $file \n";
            echo "Tipo de archivo: " . filetype($ruta . $file) . "\n";
            echo "Tamaño del archivo: " . filesize($ruta . $file) . "\n";
            echo "Ultimo acceso: " . fileatime($ruta . $file) . "\n";
            echo "Ultima modificacion: " . filemtime($ruta . $file) . "\n";

            if (is_dir($ruta . $file) && $file!="." && $file!=".."){
               //solo si el archivo es un directorio, distinto que "." y ".."
               echo "<br>Directorio: $ruta$file";
               listar($ruta . $file . "/");
            }
         }
      closedir($dr);
      }
   }else
      echo "<br>No es ruta valida";
}

Este codigo te devolvera algunos de los parametros mas importantes que puedes necesitar de un archivo, si de todas formas necesitaras mas, en esta web hay algunos mas bastante bien explicados:
http://www.desarrolloweb.com/articulos/1930.php

Saludos! espero que te funcione y que sirva!

Última edición por ivanguillen; 22/12/2007 a las 11:23
  #5 (permalink)  
Antiguo 23/12/2007, 03:00
 
Fecha de Ingreso: julio-2007
Mensajes: 75
Antigüedad: 16 años, 9 meses
Puntos: 0
Re: Script explorador de archivos

Muchas gracias voy a probarlo y te cuento, gracias!!!!!
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:57.