Scan current folder using PHP - php

I have a folder structure like this:
/articles
.index.php
.second.php
.third.php
.fourth.php
If I'm writing my code in second.php, how can I scan the current folder(articles)?
Thanks

$files = glob(dirname(__FILE__) . "/*.php");
http://php.net/manual/en/function.glob.php

foreach (scandir('.') as $file)
echo $file . "\n";

From the PHP manual:
$dir = new DirectoryIterator(dirname($path));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}

<?php
$path = new DirectoryIterator('/articles');
foreach ($path as $file) {
echo $file->getFilename() . "\t";
echo $file->getSize() . "\t";
echo $file->getOwner() . "\t";
echo $file->getMTime() . "\n";
}
?>
From The Standard PHP Library (SPL)

It depends on what you mean by 'scan' I'm assuming you want to do something like this:
$dir_handle = opendir(".");
while($file = readdir($dir_handle)){
//do stuff with $file
}

try this
$dir = glob(dirname(__FILE__));
$directory = array_diff(scandir($dir[0]), array('..', '.'));
print_r($directory);

Scan current folder
$zip = new ZipArchive();
$x = $zip->open($filepath);
if ($x === true) {
$zip->extractTo($uploadPath); // place in the directory
$zip->close();
$fileArray = scandir($uploadPath);
unlink($filepath);
}
foreach ($fileArray as $file) {
if ('.' === $file || '..' === $file)
continue;
if (!is_dir("$file")){
//do stuff with $file
}
}

List all images inside a folder
$dir = glob(dirname(__FILE__));
$path = $dir[0].'\\images';
$imagePaths = array_diff( scandir( $path ), array('.', '..', 'Thumbs.db'));
?>
<ul style="overflow-y: auto; max-height: 80vh;">
<?php
foreach($imagePaths as $imagePath)
{
?>
<li><?php echo '<img class="pagina" src="images/'.$imagePath.'" />'; ?></li>
<?php
}
?>
</ul>

Related

List images from a directory depending the uploaded date

I have a piece of code that print images from a directory.
<?
$directory = 'assets/images/';
$files = glob($directory."*.{jpg}", GLOB_BRACE);
$filecount = count($files);
for($i=1; $i<=$filecount; $i++) {
echo '<img src="'.$file.'" class="img-responsive">';
}
?>
It's working perfectly.
Except that I want to display my image depending the uploaded date.
Is it possible please ?
Thanks.
Try this:
function listdir_by_date($path){
$dir = opendir($path);
$list = array();
while($file = readdir($dir)){
if ($file != '.' and $file != '..'){
// add the filename, to be sure not to
// overwrite a array key
$ctime = filectime($data_path . $file) . ',' . $file;
$list[$ctime] = $file;
}
}
closedir($dir);
krsort($list);
return $list;
}
Reference
Okie, give this a go, using your glob method:
$directory = 'assets/images/';
$images = [];
$files = glob($directory . '*.{jpg}', GLOB_BRACE);
foreach($files as $file) {
$images[] = [filectime($file), $file];
}
array_multisort($images, SORT_DESC);
foreach ($images as $image) {
echo '<img src="' . $image[1] . '" class="img-responsive"><br>';
}
Just a slightly different method then what #mayank-pandey presented, but same basic end results.

Search for a folder and and get the content of the files inside

I'm trying to search for a folder and retrieve the files inside of the folder (get content) I'm able to search for the folder using the follow code but I can't pass from there I can't see the content an retrieve the files inside. The files inside will be txt files and I would like to be able to open and see then.
How can achieve what i want? Thank you.
<?php
$dirname = "C:\windows";//Directory to search in. *Must have a trailing slash*
$findme = $_POST["search"];
$dir = opendir($dirname);
while(false != ($file = readdir($dir))){//Loop for every item in the directory.
if(($file != ".") and ($file != "..") and ($file != ".DS_Store") and ($file !=
"search.php"))//Exclude these files from the search
{
$pos = stripos($file, $findme);
if ($pos !== false){
$thereisafile = true;//Tell the script something was found.
echo'' . $file . '<br>';
}else{
}
}
}
if (!isset($thereisafile)){
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
?>
New code
<?php
$dirname = "C:\\Windows\\";//Directory to search in. *Must have a trailing slash*
$findme = 'maxlink'; //$_POST["search"];
$files = scandir($dirname);
foreach ($files AS $file)
{
if ($file == '.' or $file == '..' or $file == '.DS_Store' or $file == 'search.php') continue;
if (stripos($file, $findme) !== false)
{
$found = true;
echo 'FOUND FILE ' . $file . '<hr>';
echo 'OPENING IT:<br>';
echo file_get_contents($dirname . $file);
echo '<hr>';
}
else
{
echo 'not found: ' . $file . '<br>';
}
}
if (!isset($found))
{
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
The following code uses a recursive function for searching the directory. I hope it’ll solve your problem.
function scandir_r($dir){
$files = array_diff(scandir($dir), array(".", ".."));
$arr = array();
foreach($files as $file){
$arr[] = $dir.DIRECTORY_SEPARATOR.$file;
if(is_dir($dir.DIRECTORY_SEPARATOR.$file)){
$arr = array_merge($arr, scandir_r($dir.DIRECTORY_SEPARATOR.$file));
}
}
return($arr);
}
$dirname = "C:\windows";
$findme = "/".preg_quote($_POST["search"], "/")."/";
$files = preg_grep($findme, scandir_r($dirname));
if(sizeof($files)){
foreach($files as $file){
$_file = $dirname.DIRECTORY_SEPARATOR.$file;
echo "$file<br/>";
}
}
else{
echo "Nothing was found.";
echo "<img src=\"yourimagehere.jpg\"/>";
}

scandir to only show folders, not files

I have a bit of PHP used to pulled a list of files from my image directory - it's used in a form to select where an uploaded image will be saved. Below is the code:
$files = array_map("htmlspecialchars", scandir("../images"));
foreach ($files as $file) {
$filelist .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $file, $file );
}
It works fine but shows all files and folders in 'images', does someone know a way to modify this code so that it only shows folder names found in the 'images' folder, not any other files.
Thanks
The easiest and quickest will be glob with GLOB_ONLYDIR flag:
foreach(glob('../images/*', GLOB_ONLYDIR) as $dir) {
$dirname = basename($dir);
}
Function is_dir() is the solution :
foreach ($files as $file) {
if(is_dir($file) and $file != "." && $file != "..") $filelist .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $file, $file );
}
The is_dir() function requires an absolute path to the item that it is checking.
$base_dir = get_home_path() . '/downloads';
//get_home_path() is a wordpress function
$sub_dirs = array();
$dir_to_check = scandir($dir);
foreach ($dir_to_check as $item){
if ($item != '..' && $item != '.' && is_dir($base_dir . "/" . $item)){
array_push($sub_dirs, $item);
}
}
You could just use your array_map function combined with glob
$folders = array_map(function($dir) {
return basename($dir);
}, glob('../images/*', GLOB_ONLYDIR));
Yes, I copied a part of it of dev-null-dweller, but I find my solution a bit more re-useable.
I try this
<?php
$dir = "../";
$a = array_map("htmlspecialchars", scandir($dir));
$no = 0; foreach ($a as $file) {
if ( strpos($file, ".") == null && $file !== "." && $file !== ".." ) {
$filelist[$no] = $file; $no ++;
}
}
print_r($filelist);
?>

Pull Images from directory - PHP

I am trying to pull images simply from my directory /img and load them dynamically into the website into the following fashion.
<img src="plates/photo1.jpg">
That's it. It seems so simple but all of the code I have found basically doesn't work.
What I have that I am trying to make work is this:
<?php
$a=array();
if ($handle = opendir('plates')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/\.png$/", $file))
$a[]=$file;
else if(preg_match("/\.jpg$/", $file))
$a[]=$file;
else if(preg_match("/\.jpeg$/", $file))
$a[]=$file;
}
closedir($handle);
}
foreach($a as $i){
echo "<img src='".$i."' />";
}
?>
This can be done very easily using glob().
$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
print "<img src=\"plates/$file\" />";
You want your source to show up as plates/photo1.jpg, but when you do echo "<img src='".$i."' />"; you are only writing the file name. Try changing it to this:
<?php
$a = array();
$dir = 'plates';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
You should use Glob instead of opendir/closedir. It's much simpler.
I'm not exactly sure what you're trying to do, but you this might get you on the right track
<?php
foreach (glob("/plates/*") as $filename) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == "png") {
// do something
} elseif($path_parts['extension'] == "jpg") {
// do something else
}
}
?>

Listing all images in a directory using PHP [duplicate]

This question already has answers here:
Getting the names of all files in a directory with PHP
(15 answers)
Closed 6 months ago.
I have the code below that lists all the images in a folder, the problem is that it finds some files ( a . and a ..) that I am not sure what they are so I am not sure how to prevent them from showing up. I am on a windows XP machine, any help would be great, thanks.
Errors: Warning: rename(images/.,images/.) [function.rename]: No error
in C:\wamp\www\Testing\listPhotosA.php on line 14
Warning: rename(images/..,images/..) [function.rename]: No error in
C:\wamp\www\Testing\listPhotosA.php on line 14
Code:
<?php
define('IMAGEPATH', 'images/');
if (is_dir(IMAGEPATH)){
$handle = opendir(IMAGEPATH);
}
else{
echo 'No image directory';
}
$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
foreach($directoryfiles as $directoryfile){
if(strlen($directoryfile) > 3){
echo '<img src="' . IMAGEPATH . $directoryfile . '" alt="' . $directoryfile . '" /> <br>';
}
}
closedir($handle); ?>
I like PHP's glob function.
foreach(glob(IMAGEPATH.'*') as $filename){
echo basename($filename) . "\n";
}
glob() is case sensitive and the wildcard * will return all files, so I specified the extension here so you don't have to do the filtering work
$d = 'path/to/images/';
foreach(glob($d.'*.{jpg,JPG,jpeg,JPEG,png,PNG}',GLOB_BRACE) as $file){
$imag[] = basename($file);
}
Use glob function.
<?php
define('IMAGEPATH', 'images/');
foreach(glob(IMAGEPATH.'*') as $filename){
$imag[] = basename($filename);
}
print_r($imag);
?>
You got all images in array format
To get all jpg images in all dirs and subdirs inside a folder:
function getAllDirs($directory, $directory_seperator) {
$dirs = array_map(function ($item) use ($directory_seperator) {
return $item . $directory_seperator;
}, array_filter(glob($directory . '*'), 'is_dir'));
foreach ($dirs AS $dir) {
$dirs = array_merge($dirs, getAllDirs($dir, $directory_seperator));
}
return $dirs;
}
function getAllImgs($directory) {
$resizedFilePath = array();
foreach ($directory AS $dir) {
foreach (glob($dir . '*.jpg') as $filename) {
array_push($resizedFilePath, $filename);
}
}
return $resizedFilePath;
}
$directory = "C:/xampp/htdocs/images/";
$directory_seperator = "/";
$allimages = getAllImgs(getAllDirs($directory, $directory_seperator));
Using balphp's scan_dir function:
https://github.com/balupton/balphp/blob/765ee3cfc4814ab05bf3b5512b62b8b984fe0369/lib/core/functions/_scan_dir.funcs.php
scan_dir($dirPath, array('pattern'=>'image'));
Will return an array of all files that are images in that path and all subdirectories, using a $path => $filename structure. To turn off scanning subdirectories, set the recurse option to false
Please use the following code to read images from the folder.
function readDataFromImageFolder() {
$imageFolderName = 14;
$base = dirname(__FILE__);
$dirname = $base.DS.'images'.DS.$imageFolderName.DS;
$files = array();
if (!file_exists($dirname)) {
echo "The directory $dirname not exists.".PHP_EOL;
exit;
} else {
echo "The directory $dirname exists.".PHP_EOL;
$dh = opendir( $dirname );
while (false !== ($filename = readdir($dh))) {
if ($filename === '.' || $filename === '..') continue;
$files[] = $dirname.$filename;
}
uploadImages( $files );
}
}
Please click here for detailed explanation.
http://www.pearlbells.co.uk/code-snippets/read-images-folder-php/
You can use OPP oriented DirectoryIterator class.
foreach (new DirectoryIterator(IMAGEPATH) as $fileInfo) {
// Removing dots
if($fileInfo->isDot()) {
continue;
}
// You have all necessary data in $fileInfo
echo $fileInfo->getFilename() . "<br>\n";
}
while (($file = readdir($handle)) !== false) {
if (
($file == '.')||
($file == '..')
) {
continue;
}
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}

Categories