This is a part two to my previous question that got answered Php Browsing Multiple Directories
Now that I got the script reading the directories perfectly, Is it possible to load the results of the file listings into a new page like races.php to "pretty it up"
Here is how it's listing the files Example of Files being listed from server
I would really like to have that be displayed inside of the site instead of jumping out into a apache server listing so its more user friendly.
EDIT
I think what I'm trying to do in theory that is once the script scans the dir it puts it into an array called $files I then foreach loop it for all of the folders but where I get stuck now is how do I pass that $file into a new page ? and make it show the contents inside the folder :)
Thanks again and sorry super newbie here trying to learn!
Script File to generate list and click to files inside of each:
<?php
$files = array();
$dir = opendir('races/ob/');
// $dir = opendir('races/ob/');
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "index.php")) {
$files[] = $file; // put in array.
}
}
natsort($files); // sort.
// print.
foreach($files as $file) {
echo("<span class='txt-spacing'><a href='races/ob/$file'>$file</a> <br />\n</>");
}
?>
The simple function can do all for you
scandir(<path>);
It will give you list of all files in the directory.
I figured out my problem with some help from a friend. I hope others can use this to help out the community.
1) First thing is to list A directory of files on the index.php
2) Once the user clicks the generated folder, go into races.php and display the the results of the files listed inside the folder clicked.
Here is how it's done by passing a parameter in the URL
index.php
<?php
$files = array();
$dir = opendir('races/ob/');
// $dir = opendir('races/ob/');
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "index.php")) {
$files[] = $file; // put in array.
}
}
natsort($files); // sort.
// print.
foreach($files as $file) {
$url = "races/ob/$file";
$path = urlencode($url);
echo("<span class='txt-spacing'>
<a href='races.php?race=$path'>$file</a> <br />\n</>");
}
?>
races.php
<?php
$path = $_GET['race'];
// right here, you need the path prefix
$path = '/public_html' . urldecode($path); //SERVER PATH
// above here you need it
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
$fileData = array();
foreach($objects as $name => $object){
$fileinfo = pathinfo($name);
if (!is_dir($name) && isset($fileinfo['extension'])) {
$file = $fileinfo['basename'];
$fileData[] = $file;
}
}
?>
<?php foreach($fileData as $file): ?>
<a target = '_blank' href="http://crpu.ca<?php echo urldecode($_GET['race']) . '/' . $file; ?>"><?php echo "$file<br>"; ?></a>
<?php endforeach; ?>
Related
I would like to list all .jpg files from folders and subfolders.
I have that simple code:
<?php
// directory
$directory = "img/*/";
// file type
$images = glob("" . $directory . "*.jpg");
foreach ($images as $image) {
echo $image."<br>";
}
?>
But that lists .jpg files from img folder and one down.
How to scan all subfolders?
Php coming with the DirectoryIterator which can be very useful in that case.
Please note that this simple function can be easly improved by adding the whole path to a file instead the only file name, and maybe use something else instead of the reference.
/*
* Find all file of the given type.
* #dir : A directory from which to start the search
* #ext : The extension. XXX : Dont call it with "." separator
* #store : A REFERENCE to an array on which store the element found.
* */
function allFileOfType($dir, $ext, &$store) {
foreach(new DirectoryIterator($dir) as $subItem) {
if ($subItem->isFile() && $subItem->getExtension() == $ext)
array_push($store, $subItem->getFileName());
elseif(!$subItem->isDot() && $subItem->isDir())
allFileOfType($subItem->getPathName(), $ext, $store);
}
}
$jpgStore = array();
allFileOfType(__DIR__, "jpg", $jpgStore);
print_r($jpgStore);
As a directotry can contain subdirectories, and in their turn contains subdirectories, so we should use a recursive function. glob() is here not sufficient. This might work for you:
<?php
function getDir4JpgR($directory) {
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if($entry != "." && $entry != "..") {
$str1 = "$directory/$entry";
if(preg_match("/\.jpg$/i", $entry)) {
echo $str1 . "<br />\n";
} else {
if(is_dir($str1)) {
getDir4JpgR($str1);
}
}
}
}
closedir($handle);
}
}
//
// call the recursive function in the main block:
//
// directory
$directory = "img";
getDir4JpgR($directory);
?>
I put this into a file named listjpgr.php. And in my Chrome Browser, it gives this capture:
I have created a directory with some files in there:
index.php
one.txt
two.txt
three.txt
four.txt
In the index.php page, I am currently using this code to echo out all of the files within the directory:
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry\n";
}
}
closedir($handle);
}
?>
Now, if anyone views the index.php page, this is what they'll see:
one.txt two.txt three.txt four.txt
As you can see from the PHP code, index.php is blacklisted so it is not echoed out.
However, I would like to go a step further than this and echo out the contents of each text file rather than the filenames. With the new PHP code (that I need help with creating), whenever someone visits the index.php page, this is what they'll now see:
(Please ignore what is in the asterisks, they are not a part of the code, they just indicate what each text file contains)
Hello ** this is what the file **one.txt** contains **
ok ** this is what the file **two.txt** contains **
goodbye ** this is what the file **three.txt** contains **
text ** this is what the file **four.txt** contains **
Overall:
I would like to echo out the contents of every file in the directory (they are all text files) aside from index.php.
You could use file_get_contents to put the file into a string.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo "$entry " . file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
Furthermore, you could use PHP's glob function to filter only the .txt files out, that way you do not have to blacklist files if you're going to be adding more files to that directory that need ignored.
Here is how it would be done using the glob function.
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename " . file_get_contents($filename) . "\n";
}
?>
This would print the contents of the files. You can do some workaround if the path is not the current path and writing some kind of boundary between the files contents.
<?php
$blacklist = array("index.php");
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $blacklist)) {
echo file_get_contents($entry) . "\n";
}
}
closedir($handle);
}
?>
I hope this helps you.
Never reinvent the wheel. Use composer.
Require symfony/finder
use Symfony\Component\Finder\Finder;
class Foo
{
public function getTextFileContents($dir)
{
$finder = (new Finder())->files()->name('*.txt');
foreach ($finder->in($dir) as $file) {
$contents = $file->getContents();
// do something while file contents...
}
}
}
I would give a chance to some SPL filesystem iterators to accomplish such this task:
$dir = '/home/mydirectory';
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
$rdi = new \RegexIterator($rdi, '/\.txt$/i');
$iterator = new \RecursiveIteratorIterator($rdi, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $file) {
echo 'Contents of the '.$file->getPathname().' is: ';
echo file_get_contents($file->getPathname());
}
This will recursively find & iterate all .txt files in given directory, including sub-directories.
Since each $file in iteration is a FilesystemIterator instance, you can use all related methods for additional controls like $file->isLink() (true for symbolic links), $file->isReadable() (false for unreadable files) etc..
If you don't want lookup sub-folders, just change the RecursiveDirectoryIterator in the second line from:
$rdi = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
to:
$rdi = new \DirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
Hope it helps.
As #brock-b said, you could use glob to get the full list of files and file_get_contents to grab the contents:
$blacklist = array('index.php');
$files = glob('*.txt'); # could be *.* if needed
foreach ($files as $file) {
if (!in_array(basename($file), $blacklist)) {
echo file_get_contents($file);
}
}
Note: the blacklist wont be hit since you're seeking for *.txt files. Only useful when doing an *.* or *.php file search
Need help for a php script / page for generating links to folders.
Have a homepage with photos that I upload using Lightroom – each album in a separate folder.
The structure is:
mysite.com
|--images
|--folder1
|--folder2
|--folder3
.
.
So I would like to end up with a dynamic index.php file that generates links to all the subfolders of “images” instead of the static index.html file I got in the root of mysite.com:
<html>
<body>
folder1
folder2
folder3
.
.
</body>
</html>
Thanx in advance
<?php
$files = scandir();
$dirs = array(); // contains all your images folder
foreach ($files as $file) {
if (is_dir($file)) {
$dirs[] = $file;
}
}
?>
use dirs array for dynamically generating links
Maybe something like this:
$dir = "mysite.com/images/";
$dh = opendir($dir);
while ($f = readdir($dh)) {
$fullpath = $dir."/".$f;
if ($f{0} == "." || !is_dir($fullpath)) continue;
echo "$f\n";
}
closedir($dh);
When I need everything (i.e., something/*), I prefer readdir() over glob() because of speed and less memory consumption (reading a directory file by file, instead of getting the whole thing in an array).
If I'm not mistaken, glob() does omit .*files and has no need for the $fullpath variable, so if you're after speed, you might want to do some testing.
Try something like this:
$contents = glob('mysite.com/images/*');
foreach ($contents as content) {
$path = explode('/', $content);
$folder = array_pop($path);
echo '' . $folder . '';
}
Or also this:
if ($handle = opendir('mysite.com/images/') {
while (false !== ($content = readdir($handle))) {
echo echo '' . $content . '';
}
closedir($handle);
}
I'm working on a small script and I want to list the contents of a directory, make them into hyperlinks, and then edit those hyperlinks to look pretty (I.e. not show an ugly super long path name), then limit the number files echoed back to the browser. Also, I need the most recent files echoed back only.
I was thinking about using this:
<?php
$path = "/full/path/to/files";
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$files .= ''.$file.'';
}
}
closedir($handle);
}
?>
or this:
<?php
$sub = ($_GET['dir']);
$path = 'enter/your/directory/here/';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
if($file != "." && $file != "..") {
if (substr($file, -4, -3) =="."){
echo "$i. $file <br />";
}else{
echo "$i. <a href='?dir=$sub/$file'>$file</a><br />";
}
$i++;
}
}
closedir($dh);
?>
But I dont want to list the files like this:
C:/example/example2/Hello.pdf
I want to edit the variable. Is that possible? To make it say something as simple as "Hello."
I want to limit the amount of files listed as well. For example: only list the first 5 files, or last 5, etc. Is there a function or some kind of parameter for that?
I appreciate any help or push in the right direction. Thanks
I'm on my phone so providing a code example will be tough. Why not iterate through the directories, storing the file name in an array, with the absolute path as the value for that key?
EDIT: You can use basename to aid you in doing this.
Every 72 hours I upload a new PHP file to my server. (well actually it is an xml file transformed on the server with php) Is there a method to create a link on an html page that links to the "new" PHP doc automatically everytime a new file is uploaded?
I don't want to manually change the link every 72 hours. I would ultimately like to have an html page with a list of links to every new doc that is uploaded. I found this for images but I need someting like this but for PHP files and links.
http://net.tutsplus.com/articles/news/scanning-folders-with-php/
Any help would be very appreciated.
I found a solution that add links to the xml files. Now I just need to figure out how to add a link to reference the xslt sheet for each new xml file that is upload AUTOMATICALLY. I am not sure how to do this but any help would be very helpful. Thanks for everyones help.
<?php
$count = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {$count++;
print("".$file."<br />\n");
}
}
echo '<br /><br />Return';
closedir($handle);
}
?>
To read in a directory of files and then sort them by upload time you can just use:
$files = glob("files/*.xml");
$files = array_combine($files, array_map("filemtime", $files));
arsort($files);
print "link: " . current($files); // make that an actual <a href=
You can do that pretty easily with PHP function readdir:
http://php.net/manual/en/function.readdir.php
Simply loop through the files in the directory where you upload files and have php output a link for each.
ie:
<?php
if ($handle = opendir('/path/to/upload_dir')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo '' . $file . '<br />';
}
}
closedir($handle);
}
?>
You'll need to edit the http:// URL on the href to point to the correct download URL for your server, as well as the server path for opendir.
Hope that helps.
list by filetype
<?php
if ($handle = opendir('/path/to/dir')) {
while (false !== ($file = readdir($handle))) {
if (strpos($file, '.php',1)||strpos($file, '.xml',1) ) {
echo "<p>$file</p>";
}
}
closedir($handle);
}