Php link directory add article

New Page

How to link and loop through subdirectories using php

Ask

Asked 1 year, 4 months ago

Modified 1 year, 4 months ago

viewed 107 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

Follow

Follow this question to receive notifications

asked on May 21, 2021 at 6:04 PM

User avatar Erfan Ahmed Siam

Erfan Ahmed Siam Erfan Ahmed Siam

15 5 5 bronze badges

of them

  • Not sure what you mean by working 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 answers2

Sorted by: Reset to default

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

Cette réponse est utile

0

Cette réponse n’est pas utile

Afficher l’activité sur ce post.

Aquí hay un método para hacer eso que también emplea un nivel de seguridad. Si bien esto puede ser solo un proyecto escolar o un tutorial, siempre debe considerar la seguridad. He comentado a continuación, pero básicamente esto es lo que está sucediendo.

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 – don’t allow file browser to exit 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 removes the ../ and the ./ and the .. which makes upward traversal possible despite our checks // if our root directory is not present in the $dir if (strpos($dir, $rootDirectory) = == false ) $dir = $rootDirectory; // if our root directory is not the very first part of $dir if (strpos($dir, $rootDirectory) !== 0 ) $dir = $rootDirectory; $folders= new DirectoryIterator($dir); while($folders->valid()){ // set 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(); } ?>

compare

Share a link to this answer

Copy link CC BY-SA 4.0

Follow

Follow this answer to receive notifications

answered on May 21, 2021 at 7:14 PM

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 helpful

0

This answer is not helpful

View activity on this post.

Strict base path for security, folder browsing with return, file browsing with viewing file contents. DIV layout, no JavaScript and simple PHP.

<?php $Script = basename(__FILE__); $RootPath = “F:\Web”; $HTMLFile = []; $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; clarify 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 solid gray; 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 solid gray; 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: 1 px Black solid; background: rgba (255, 0, 255, 0.25); padding: 5px;}.FileContent > .Content{height: calc(100% – 1em – 12px); bottom : black ; padding: 5px; White colour ; whitespace: pre;} </style> </head> <body> <div class=” <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> <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> 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> 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> ?=isset($_GET[“File” ])? file_get_contents(“{$Path}/{$_GET[“File”]}”) : null ?></div> </div> </body> </html> ?=isset($_GET[“File”] )? file_get_contents(“{$Path}/{$_GET[“File”]}”): null ?></div> </div> </body> </html>

Compartir

Partager un lien vers cette réponse

Copier le lien CC BY-SA 4.0

Suivre

Suivez cette réponse pour recevoir des notifications

édité le 21 mai 2021 à 19:37

répondu le 21 mai 2021 à 19:21

Broken Arrow user avatar

Flèche brisée Flèche brisée

549 3 3 insignes d’argent 11 11 insignes de bronze

Ajouter un commentaire | 

Ta Réponse

Merci d’avoir contribué à une réponse à Stack Overflow !

  • Veuillez vous assurer de répondre à la question. Fournissez des détails et partagez vos recherches !

Mais évitez…

  • Demander de l’aide, des éclaircissements ou répondre à d’autres réponses.
  • Faire des déclarations basées sur une opinion ; étayez-les par des références ou une expérience personnelle.

Pour en savoir plus, consultez nos conseils pour rédiger de bonnes réponses.

brouillon enregistré

Brouillon rejeté

Inscrivez-vous ou connectez-vous

Inscrivez-vous avec Google

Sign up using Facebook

Sign up using your email and password

Submit

Post as guest

Yam

E-mail

Required, but never displayed

Post as guest

Yam

E-mail

Required, but never displayed

Post your answer Ignore

By clicking “Post your answer” you agree to our Terms of Service, Privacy Policy and Cookies Policy

Not the answer you are looking for? Browse other tagged questions

  • php
  • phone book
  • to analyse

or ask your own question.

  • The overflow blog
  • Five Nines Uptime Without Developer Attrition (Ep. 488)

  • We Hate Scrum and Agile… When Done Badly (Ep. 489)

  • Featured in Meta
  • Recent color contrast changes and accessibility updates

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

  • 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?

2148

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

2229

How does PHP ‘foreach’ actually work?

1194

List only directories using ls in Bash?

burning questions from the net

  • How do non-English speakers navigate JFK airport?
  • Why does the expected value in quantum mechanics correspond to the classically measured value?
  • Can I upgrade a mountain bike from ten years ago to modern standards?
  • How do I request “open to”?
  • Python decibels with metric precision?
  • Can stem+そう mean rumors?
  • How many syllables do these rules say ‘each’ has?
  • Does scintillating spell metamagic apply to minor spells (e.g. Lightning Arc)?
  • Is a monarch’s title and royal seal changed if the queen has the same name as her former king?
  • Rationale for using Saturn as a future colonization base
  • How important is having multiple gears on an e-bike?
  • What video game is Spiderhead (2022) playing?
  • What do I need in my ~/.vimrc to make neovim act like vim?
  • Adding a Rotating RGB Border to a Model
  • Is it illegal to work for someone else while on paid leave?
  • Send an email to a colleague in times of mourning
  • Why do car flashing lights flash twice as fast when a flashing light is burnt out?
  • Can I add heavy cream to whipped cream to increase the fat content and make the whipped cream more stable?
  • Why does space warfare not lead to the total annihilation of both sides?
  • Is it acceptable to resubmit a manuscript to another publisher if there is no response after three months?
  • What is the area of ​​the SSME nozzle knowing only thrust at sea level and in a vacuum?
  • Has Batman ever been produced as an Arkham fan theory inmate in any medium?
  • What is the use case for disabling an index?
  • Are there any countries in Europe where there is a numerical threshold of 10% (or similar, but low) for minority language rights?

question flow

Subscribe to RSS

question flow

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.


Video Php link directory add article

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…