File browser

Open and read files in directory inside folder in PHP

So I am trying to create a file server, Basicaly the way it should work is you have lots of folders that contain files and when you click on a file you will download it, if it is a folder you can open it and see the content inside it. I have this root directory that contains folder and php file as below .

Open and read files in directory inside folder in PHP

Okay guys so I am a bit lost as to how to adjust my code. Up to now, I have my code to read any Json file in a directory, parse it and put it in a table — works great since I was only using 1 JSON file per table row.

What I need to do now is the following, each IP address I have gives me 3 JSON files now that are placed into a folder with the IP address as its name. In my main directory I will have many folder each with 3 JSON files in it.

I want to read each file in every folder, place the info I parse in a table and then move on to the next folder as a new row and do the same.

FOR REFERENCE:: Current file layout: FOLDER-->JSON -->JSON -->JSON New file layout: FOLDER-->IPADDRESS-->JSONFILE1 -->JSONFILE2 -->JSONFILE3 -->IPADDRESS2-->JSONFILE1 --JSONFILE2 -->JSONFILE3 

Current code for reading any JSON file in a directory:

 $dir = "my dir"; if (is_dir($dir)) < if ($dh = opendir($dir)) < foreach(glob("*_name.json") as $filename) < $data = file_get_contents($filename); $testing = json_decode($data, true); echo ""; echo " "; foreach($testing[0] as $row) < // code for parsing here . >> > > 

here you go using RecursiveIteratorIterator Class

 function Get_Files() < $dir = "my_dir"; $init = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)); $files = array(); foreach ($init as $file) < if ($file->isDir()) < continue; >$files[] = $file->getPathname(); > return $files; > foreach (Get_Files() as $file) < $data = file_get_contents($file); $testing = json_decode($data, true); echo ""; echo " "; > 
my_dir\192.168.0.1\JSONFILE1.json my_dir\192.168.0.1\JSONFILE2.json 

Getting the names of all files in a directory with PHP, You need to surround $file = readdir($handle) with parentheses. Here you go:

Read Local Directory and List Files in PHP

In this video we’ll learn how to read files from the local directory and list them using PHP Duration: 13:23

Читайте также:  Python join list to one string

Read and list files from directory PHP

In this PHP video tutorials we will cover Wamp, comments, variables, strings, concatenation
Duration: 6:24

Upload File in Folder or Directory

In this PHP Filesystem series video tutorial we have discussion how can we upload file in Duration: 11:23

How to use and read php file inside different folder in PHP ?

I want my .php file categorize inside the folder. I have this root directory that contains folder and php file as below .

core initial.php // database connection css style.css js js.css apply index.php apply.php templates head.php footer.php index.php 

My root index.php, I just include the file as usual. Note* — head.php and footer.php contains HTML file.

Apply'; include 'templates/footer.php'; ?> 

But my problem is, my index.php file inside apply folder cannot call initial.php.

Warning: require_once(core/initial.php): failed to open stream: No such file or directory in C:\xampp\htdocs\movement\production\index.php on line 2

Fatal error: require_once(): Failed opening required ‘core/initial.php’ (include_path=’\xampp\php\PEAR’) in root\test\apply\index.php on line 2

The reason is I don’t want my .php file all located in root directory. I want each php file except index.php in their own folder.

How can I do that ? Can someone help me on this problem ?

In initial.php or some other helper file, do:

/** List of all dirs you wish to include from, relative to the document root */ const INCLUDE_DIRS = [ '/', '/core/', '/apply/', '/templates/' ]; function getPath($filename) < $rootDir = $_SERVER['DOCUMENT_ROOT']; $path = null; foreach(INCLUDE_DIRS as $dir)< if(file_exists($path =$rootDir . $dir . $filename)) return $path; >throw new Exception("Could not find $filename in any of the INCLUDE_DIRS directories"); > 

Now you only have to get a single include right; the file that holds the function. Always include it using a full path so it will work from anywhere:

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/initial.php' 

You can go even further and make use of the auto_prepend_file directive which tells PHP to always execute that file before running the regular script. That’s a great file to have the function above, and PHP will include it for you automatically.

Anyway, once the file with getPath() is included, you never have to worry about using the right path again. Just make sure all include directories are listed in the INCLUDE_DIRS constant and include/require your files like this:

require_once getPath('footer.php'); //getPath will scan INCLUDE_DIRS and find it 

Note an important limitation of this approach is that if you have two files by the same name, it won’t work because the first one found will be included. In that case, just be sure to always use the full path when including/requiring starting with $_SERVER[‘DOCUMENT_ROOT’]

require_once $_SERVER['DOCUMENT_ROOT'] . '/core/initial.php'; include $_SERVER['DOCUMENT_ROOT'] . '/templates/head.php'; 

Why not just always link based on root like:

 require_once '/core/initial.php'; include '/templates/head.php'; 

Relative path doesn’t work with Windows. On linux it does.

Читайте также:  Form value length javascript

The best is to define a constant in a root file called defines.php and call it in index.php with require_once.

After that, you will use this absolute path in all require and includes like it :

apply/index.php

require_once _APP_ROOT_ . 'core/initial.php'; include _APP_ROOT_ . 'templates/overall/header.php'; 

You can find more info here : PHP — include() or require() with relative paths won’t work on windows, even when appending __DIR__

PHP script to loop through all of the files in a directory?, You can use the DirectoryIterator. Example from php Manual:

PHP how to display folder and its content while also being able to download the content

So I am trying to create a file server,

Basicaly the way it should work is you have lots of folders that contain files and when you click on a file you will download it, if it is a folder you can open it and see the content inside it.

My question is how can I create such system ? I have been trying to use FilesystemIterator but I do not know how to proceed further.

this is my PHP code that I am using, this code is set inside of div element

And this is my file structure file structure

I know that it is possible to create this, I just don’t know how to create it.

I’ve refactored your code a bit:

$filesInFolder = array(); $baseDir = "/var/www/html/test"; $currentDir = !empty($_GET['dir']) ? $_GET['dir'] : $baseDir; $currentDir = rtrim($currentDir, '/'); if (isset($_GET['download'])) < //you could provide another logic to present requested file readfile($_GET['download']); exit; >$iterator = new FilesystemIterator($currentDir); echo "

" . $iterator->getPath() . "

"; foreach ($iterator as $entry) < $name = $entry->getBasename(); if (is_dir($currentDir . '/' . $name)) < echo "D: " . $name . "
"; > elseif (is_file($currentDir . '/' . $name)) < echo "F: " . $name . "
"; > >

You have to be very careful because an attacker could easily change the query to ?dir=../../ and get access to your filesystem. So you have to prevent this by yourself.

Edit: It’s not working 100% but I’m trying to provide a correct answer soon

Edit2: Code refactored to working

So here is how you would do it. First you create a FileReader.php file like so ( I have also added Icons and file size, you will need to create icons folders where all your icons will be located)

 /** * @param string $path */ public function removeRootFromPath( $path) < $path = preg_replace('/' . preg_quote($this->root, '/') . '/', '', $path); $path = $this->cleanPath($path); return DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR); > /** * @param string $path */ public function addRootToPath( $path) < $path = $this->removeRootFromPath($path); $path = ltrim($path, DIRECTORY_SEPARATOR); $root = rtrim($this->root, DIRECTORY_SEPARATOR); return $root . DIRECTORY_SEPARATOR . $path; > /** * @param string $dir Directory to load */ public function cleanPath( $dir) < $sep = preg_quote(DIRECTORY_SEPARATOR, '/'); return preg_replace('/\.\.' . $sep . '|\.' . $sep . '/', '', $dir); >/** * @param string $dir Directory to load * @return FilesystemIterator|null */ public function readDirectory( $dir) < $dir = $this->addRootToPath($dir); try < return new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS); >catch (UnexpectedValueException $exception) < return null; >> /** * @param string $size File size in bytes * @param int $precision File size conversion precision * @return string round($size, $precision).$units[$i] */ public function humanFilesize($size, $precision = 1) < $units = array(' B',' kB',' MB',' GB',' TB',' PB',' EB',' ZB',' YB'); $step = 1024; $i = 0; while (($size / $step) >0.9) < $size = $size / $step; $i++; >return round($size, $precision).$units[$i]; > /** * @param string $file File to load * @return string $type return $type . "?" . $image; > > ?> 

Then you Create FileTable.php in which all of your files and folders will be displayed and you will be able to access them and download selected files (Only files not folders) + (I have added simple filtering)

 else < $cleanPath[0] = " "; break; >default: $cleanPath[0] = " "; break; > /** * HERE WRITE ALL FILES YOU WANT FileReader TO IGNORE * - WRITE file + its extension * - FOR DIRECTORY WRITE THE NAME OF THE DIRECTORY TO IGNORE */ $filesToIgnore = [ 'index.php', 'index.css', 'index.html', 'Restricted', 'PUT YOUR FILES HERE.txt' ]; ?>     removeRootFromPath(dirname($target))); ?>"> level up  File name File size File type Last file modification date   readDirectory($target)): ?>    removeRootFromPath($result->getFileInfo()); //File information $fileName = pathinfo($result,PATHINFO_BASENAME); $fileInfo = explode("?",($reader->returnFileExtensionAndImage(pathinfo($result,PATHINFO_EXTENSION))),2); $fileExtension = $fileInfo[0]; $fileIcon = $iconsPath . $fileInfo[1]; $fileDateModified = explode(" ",date("F d.Y - H:i:s",filemtime($result)),4); $fileDateModified = implode(" ",$fileDateModified); $type = $result->getType(); if($type !== 'dir')< $fileSize = $reader->humanFilesize(filesize($result)); > ?>  ">   "> ">        Directory/File doesn't exist    

And at last you will create index.php where you will connect this together

 removeRootFromPath(!empty($_GET['path']) ? $_GET['path'] : '/'); ?>      >   

Should you need it -> CODE HERE Simply download it and put it in your htdocs folder if you are using Apache

List all files in one directory PHP [duplicate], Show activity on this post. You are looking for the command scandir. I experienced a small snag finding the directory. $files = array_diff(scandir(__DIR__ .

Источник

Оцените статью