I have user folder /folder_name and there are files with name prefix
Example this pattern id_radom.example
5__1490952185fed525d92.24525311.jpg
15__4658521860030a66d0.90328377.jpg
15__6654521861778060e1.31100475.jpg
15__6654521861778060e1.31100475.jpg
I want to display all of these image(id=15) using php
I am trying:
$path = "uploads/registered_files/".$_SESSION['user_data']['username'];
$a = glob("/".$path."/".$article->article_id."__",GLOB_BRACE);
print_r($a);
But I got empty array()
Solution may look like this:
if (false === ($handle = opendir($path))) {
//catch error here
}
$images = array();
while (false !== ($file = readdir($handle))) {
preg_match('/^15__.*/', $file)) and $images[] = $file;
}
closedir($handle);
foreach ($images as $image) {
echo '<img src="',$path,DIRECTORY_SEPARATOR,$image,'"/>';
}
/".$path."/".$article->article_id."__" is pointing to the root of the filesystem, not to the root of your website. This might be the problem.
Try removing the first / or prefix it with the absolute path to your website's root.
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
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; ?>
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);
}
(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}