Add article php link directory

New Page

How to link and track subdirectories using php

interrogate

I ask 1 year, 4 months ago

I modified 1 year, 4 months ago

viewed 109 times

This question shows research effort; it is useful and clear

0

This question shows no research effort; unclear or not useful

Please mark this question.

View activity on this post.

I want to make a simple file browser using PHP. As I am new here for PHP. i need a helping hand

<table class=”table”> <thead> <tr> <th scope=”col”>Directory Name</th> <th scope=”col”>Last Modified</th> <th scope=”col”> Size</th> </tr> </thead> <tbody> <?php $folders= new DirectoryIterator(__DIR__); while($folders->valid()){ ?> <tr> <td><?php echo “<a href='{$folders->current()}’>{$folders->current()}< /a>” ?></td> <td></td> <td><?php echo $folders->getSize();?></td> </tr> <?php $folders->next (); } ?> </tbody></table>

I’ve come this far. How can I complete this code to have a working file browser using php. Thanks.

  • php
  • phone book
  • to analyse

To share

Share a link to this question

Copy link CC BY-SA 4.0

improve this question

Follow

Follow this question to receive notifications

requested on May 21, 2021 at 6:04 p.m.

User avatar Erfan Ahmed Siam

Erfan Ahmed Siam Erfan Ahmed Siam

fifteen 5 5 bronze badges

of them

  • I don’t know what you mean by functional file browser. Is there anything wrong with what you’ve done so far? If you’re having trouble with a specific piece of code, ask about it.

    –Kinglish

    May 21, 2021 at 6:09 PM

  • as far as I’m here, it only prints the directory name! How do I href its child directories?

    – Erfan Ahmed Siam

    May 21, 2021 at 6:20 p.m.

Add a comment | 

2 answerstwo

Sorted by: Reset to default

Score le plus élevé (par défaut) Tendance (les votes récents comptent plus) Date de modification (la plus récente en premier) Date de création (la plus ancienne en premier)

Cette réponse est utile

0

Cette réponse n’est pas utile

Afficher l’activité sur ce post.

Voici une méthode pour le faire qui utilise également un niveau de sécurité. Bien qu’il ne s’agisse que d’un projet scolaire ou d’un didacticiel, vous devez toujours tenir compte de la sécurité. J’ai commenté ci-dessous, mais c’est essentiellement ce qui se passe.

Primero establece un $rootDirectory(que tendrá que modificar; este está configurado en mi sistema de archivos). El rootDirectory es lo más lejos que permitirá que vaya el navegador, porque como puede ver, el pequeño ..enlace en la parte superior de cada carpeta/lista de archivos permite el recorrido del directorio hacia arriba y cualquiera puede navegar por sí mismo a cosas que no desea. jamás exponer.

Los enlaces a las carpetas enumeradas se modifican para pasar a lo largo de la ruta a esa carpeta DESDE el directorio raíz. De esa manera, nadie podría falsificar un enlace a alguna carpeta interna del sistema operativo. Los enlaces pasan por este camino en una GETvariable ( ?dir=/some/path/). Cuando la página se carga, busca esa GETvariable, agrega el directorio raíz al principio y lo somete a un par de comprobaciones para asegurarse de que sea un directorio real, que no esté fuera de nuestro directorio raíz, etc. primero convirtiéndolo con realpath(). La variable entrante dirpodría ser /myRootDirectory/../../../etc/mySecretConfigFile.confla que pasaría nuestra verificación porque tiene el directorio raíz en ella. realpath()elimina todo eso ../para que podamos trabajar con él.

<table class=”table”> <thead> <tr> <th scope=”col”>Directory Name</th> <th scope=”col”>Last Modified</th> <th scope=”col”> Size</th> </tr> </thead> <tbody> <?php // simple security – do not allow the file browser to get out of this root directory // SET THIS FOR YOUR SYSTEM $rootDirectory = ‘/Users /laphona/Sites/htdocs’; // $dir = __DIR__; if ($_GET && $_GET[‘dir’]) $dir = $rootDirectory . $_GET[‘dir’]; else $dir = $rootDirectory; $dir = realpath($dir); // this takes out the ../ and the ./ and the .. that makes upward traversal possible despite our checks // if our root directory isn’t present in the $dir if (strpos($dir, $rootDirectory) = == false ) $dir = $rootDirectory; // if our root directory isn’t the very first part of the $dir if (strpos($dir, $rootDirectory) !== 0 ) $dir = $rootDirectory; $folders= new DirectoryIterator($dir); while($folders->valid()){ // set up the path here to be the direct path to the folder, minus our root directory $myPath = str_replace($rootDirectory, ”, $folders->getPath()) . “/” . $folders->current(); $myItem = “<a href='”.$_SERVER[‘PHP_SELF’]..”?dir={$myPath}’>{$folders->current()}</a>”; // if it’s a file just present the name, no link if ($folders->isFile()) $myItem = $folders->current(); ?> <tr> <td><?php echo $myItem ?></td> <td></td> <td><?php echo $folders->getSize();?></td> </ tr> <?php $folders->next(); } ?>

Share

Share a link to this answer

Copy link CC BY-SA 4.0

improve this respuesta

Seguir

Sigue esta respuesta para recibir notifications

answered May 21, 2021 at 19:14

Kinglish user avatar

Kinglish Kinglish

22.1k 3 3 gold badges 22 22 silver badges 41 41 bronze badges

0

Add a comment | 

This answer is useful

0

This answer is not useful

Show activity on this post.

Strict base path for security, folder navigation with back, file navigation with file content view. DIV layout, no JavaScript and simple PHP.

<?php$Script = basename(__FILE__);$RootPath = “F:\Web”;$FileHTML = [];$Path = realpath(“” . (isset($_GET[“Path”]) ? $_GET[ “Path”] : $RootPath).”” .(isset($_GET[“Folder”]) ? “/{$_GET[“Folder”]}”: null));if(substr($Path, 0, strlen($RootPath)) !== $RootPath)$Path = $RootPath;foreach(scandir($Path) as $Item)if($Item != “.” && ($Path != $RootPath || $Item != “..”)){ $ItemWithPath = “{$Path}/{$Item}”; if(is_dir($ItemWithPath)){ $FolderHTML[] = “<div class=\”Item\”><a href=\”./{$Script}?Path={$Path}&Folder={$Item} \” class=\”Link\”>{$Item}</a></div>”; } else{ //$FileHTML[] = “<div class=\”Item\”><a href=\”./{$Script}?Path={$Path}& Folder=.&{$Item}&File={$Item}\” class=\”Link\”>{$Item}</a><span class=\”Size\”>” . round(filesize($ItemWithPath) / 1024, 0) . ” KB</span><span class=\”ModificationTime\”>” . date(“Ymd H:i:s”, filemtime($ItemWithPath)) . “KB</span></div>”; $FileHTML[] = “<tr class=\”Item\”><td><a href=\”./{$Script}?Path={$Path}&Folder=.&{$Item}&File={$ Item}\” class=\”Link\”>{$Item}</a></td><td class=\”Size\”>” . round(filesize($ItemWithPath) / 1024, 0) . ” KB</td><td class=\”ModificationTime\”>” . date(“Ymd H:i:s”, filemtime($ItemWithPath)) . “</td></tr>”; }}?><html> < head> <style> body{margin: 0; font-family: Verdana, Tahoma, Arial; font-size: 12px;} body:after{display: block; clear: both; content: ”;} div{box-sizing: border-box;} .Navigation{float: left; width: 33%;} .Navigation > .CurrentPath{border: 1px Black solid; background: rgba(0, 255, 255, 0.25); padding: 5px;}.Navigation > .FolderList{height: calc(50% – 1em – 12px); border: 1px Gray solid; overflow-y: auto;} .Navigation > .FolderList > .Item{padding: 5px;} .Navigation > .FolderList > .Item:hover{background: rgba(255, 255, 0, 0.5);} .Navigation > . FolderList > .Item > .Link{text-decoration: none;} .Navigation > .FileList{height: 50%; border: 1px Gray solid; overflow-y: auto;} .Navigation > .FileList > table{font-size: inherit;} .Navigation > .FileList > table > tbody > .Item{} . Navigation > .FileList > table > tbody > .Item:hover{background: rgba(255, 255, 0, 0.5);} .Navigation > .FileList > table > tbody > .Item > td{padding: 5px;} .Navigation > .FileList > table > tbody > .Item > td > .Link{text-decoration: none;} .Navigation > .FileList > table > tbody > .Item > .Size{margin-left: 2em; white-space: nowrap;} .Navigation > .FileList > table > tbody > .Item > .ModificationTime{margin-left: 2em;} .FileContent{float: left; width: 67%;} .FileContent > .FileName{border: 1px Black solid; background: rgba(255, 0, 255, 0.25); padding: 5px;} .FileContent > .Content{height: calc(100% – 1em – 12px); background: Black; padding: 5px; color: White; white-space: pre;} </style> </head> <body> <div class=”Navigation”> < div class=”CurrentPath”><?=$Path?></div> <div class=”FolderList”> <?=implode(“\n “, $FolderHTML) . “\n”?> </div> <div class=”FileList”> <table> <tbody> <?=implode(“\n “, $FileHTML) . “\n”?> </tbody> </table> </div> </div> <div class=”FileContent”> <div class=”FileName”><?=isset($_GET[“File”] )? $_GET[“File”] : null?></div> <div class=”Content”><?=isset($_GET[“File”]) ? file_get_contents(“{$Path}/{$_GET[“File”]}”): null?></div> </div> </body></html> ?=implode(“\n “, $FolderHTML) . “\n”?> </div> <div class=”FileList”> <table> <tbody> <?=implode(“\n “, $FileHTML) . “\n”?> </tbody> </table> </div> </div> <div class=”FileContent”> <div class=”FileName”><?=isset($_GET[“File”] )? $_GET[“File”] : null?></div> <div class=”Content”><?=isset($_GET[“File”]) ? file_get_contents(“{$Path}/{$_GET[“File”]}”): null?></div> </div> </body></html> ?=implode(“\n “, $FolderHTML) . “\n”?> </div> <div class=”FileList”> <table> <tbody> <?=implode(“\n “, $FileHTML) . “\n”?> </tbody> </table> </div> </div> <div class=”FileContent”> <div class=”FileName”><?=isset($_GET[“File”] )? $_GET[“File”] : null?></div> <div class=”Content”><?=isset($_GET[“File”]) ? file_get_contents(“{$Path}/{$_GET[“File”]}”): null?></div> </div> </body></html> /table> </div> </div> <div class=”FileContent”> <div class=”FileName”><?=isset($_GET[“File”]) ? $_GET[“File”] : null?></div> <div class=”Content”><?=isset($_GET[“File”]) ? file_get_contents(“{$Path}/{$_GET[“File”]}”): null?></div> </div> </body></html> /table> </div> </div> <div class=”FileContent”> <div class=”FileName”><?=isset($_GET[“File”]) ? $_GET[“File”] : null?></div> <div class=”Content”><?=isset($_GET[“File”]) ? file_get_contents(“{$Path}/{$_GET[“File”]}”): null?></div> </div> </body></html>

Share

Share a link to this answer

Copy link CC BY-SA 4.0

Improve this answer

Follow

Follow this answer to receive notifications

edited May 21, 2021 at 19:37

answered May 21, 2021 at 19:21

Broken Arrow user avatar

Broken Arrow Broken Arrow

549 3 3 silver badges 12 12 bronze badges

Add a comment | 

Your Answer

Thanks for contributing an answer to StackOverflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.

saved draft

Draft rejected

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Submit

Post as a guest

Name

E-mail

Required, but never shown

Post as a guest

Name

E-mail

Required, but never shown

Post Your Answer Discard

Al hacer clic en “Publicar su respuesta”, accept our service terms, privacy policy and cookie policy

No es la respuesta que estás buscando? Explorar otras preguntas etiquetadas

  • php
  • directorio
  • scandalize

o haga su propia pregunta.

  • The overflow blog
  • Tendencias de overflow of pila: activity of the site between week and end of week

  • No dejes que el software te robe el tiempo (Ep. 491)

  • Destacado in Meta
  • Recientes cambios de contrast de color y actualizaciones de accesibilidad

  • Reviewer overboard! Or a request to improve the onboarding guide for new…

  • Collective update: recognized members, articles and GitLab

  • Do I need to explain other people’s answers in code?

Related

2773

How can I prevent SQL injection in PHP?

1239

Secure hash and salt for PHP passwords

1481

How to redirect in PHP?

1667

startsWith() and endsWith() functions in PHP

1925

How to display PHP errors?

2267

How do you parse and process HTML/XML in PHP?

2149

How do I change the permissions of a folder and its subfolders/files?

1336

“Warning: Undefined Variable”, “Warning: Undefined Index”, “Warning: Undefined Array Key” and “Warning: Undefined Offset” using PHP

2228

How does PHP ‘foreach’ actually work?

1196

List only directories using ls in Bash?

burning questions from the net

  • Has Batman ever been produced as an Arkham fan theory recluse in any medium?
  • Can I work remotely for a non-Singaporean employer while visiting Singapore?
  • Reasons not to trust Let’s Encrypt certificates
  • A colleague always asks me to do little things when they are not my responsibility.
  • How to solve this sudoku without guessing?
  • How do custom indexes negatively affect performance?
  • How to get rid of a large amount of wet sugar?
  • Is my homemade Hiccupera spell any good?
  • Ripple Voltage Filter Capacitor
  • The recipient claims that the cashier’s check will not be cashed
  • Are there any international laws that govern changing countries in a region?
  • It’s just magic
  • Is there a reason Clementi didn’t suggest switching fingers for repeating notes? (Sonatina Op. 36 No. 2)
  • Discontinuity crossing with complex background
  • Total length of intersecting lines: comparing several lines with each other
  • Solving a Recurrence Relationship
  • Why is the Wizard of Oz scarecrow wrong about the Pythagorean theorem?
  • Is James Earl Jones the actor who has played the same sci-fi character the longest?
  • Free-electron lidar counter?
  • What academic writing style allows for detailed explanatory footnotes?
  • Does the key in which a piece is written affect the playability of the piano?
  • Do movie studios need permission to use an AI recreation of an actor’s voice in their works?
  • Can we realize a smooth manifold like the image of a smooth function?
  • What is it called and what causes it? Bright reflections along the contrasting edges

question flow

Subscribe to RSS

question flow

Bessere Übersetzung vorschlagen


Video Add article php link directory

Related Posts

Free chat room code for my website

Contents1 How to set up a free chat room on the website.2 3 comentarios2.1 Trackbacks/Pingbacks2.2 Submit a Comment Cancel reply3 How to Create a Chat Room Website…

Background image full screen css

Contents1 Cómo – Full Page Image1.1 Example1.2 Example2 CSS background image tamaño tutorial: how to codify a complete page background image3 Perfect Full Page Background Image3.1 Méthode CSS géniale,…

WordPress leverage browser caching

Contents1 Aproveche el almacenamiento in hidden del navegador1.1 Will it works for my website?1.2 Where are plugin options1.3 Some JavaScript files still display under Leverage Browser Caching1.4…

WordPress post to facebook page

Contents1 How to Automatically Post to Facebook from WordPress1.1 Download Now: How to Launch a WordPress Website [Free Guide + Checklist]1.2 1. Create an IFTTT account.1.3 2….

Download images from wordpress media library

Contents1 How to export your WordPress media library1.1 Download maintenant : How to launch a WordPress website [Free Guide + Checklist]1.2 How to export your WordPress media…

WordPress single post template

Contents1 How to Create Custom Unique Post Templates in WordPress2 Post Template Files2.1 author.php2.2 Fecha.php3 Handbook navigation4 How to Create Custom Single Post Templates in WordPress5 Video…