php function not extracting all images from directory - php

my code is not extracting all of the files inside the directory and i donde know why, i dont have any extension restrictions or anything, ok so this is my code what am i doing wrong? there are 24 images with jpg and png extensions and only 13 are detected when i print_r($arr)
:
<?php
function loadimages($dir) {
if(substr($dir, -1) != "/") $dir .= "/";
$rootdir = $_SERVER["DOCUMENT_ROOT"];
$fulldir = $rootdir."/".$dir;
$dir = opendir($fulldir);
$arr = array();
while(readdir($dir)) {
$arr[] = readdir($dir);
}
echo "<h1>".count($arr). "</h1><br />";
foreach($arr as $img) {
echo "<img src='/pages/course-images/{$img}' />";
}
}
loadimages("pages/course-images");
?>

I would use glob() instead.
$images = glob('*.{png,jpg}', GLOB_BRACE);
print_r($images);
http://php.net/manual/en/function.glob.php
It doesn't work because while(readdir($dir)), then you read one value and skips one step forward to the next file. The correct way would be this, and it's explaind in the manual.
while(false !== ($entry = readdir($dir))) {
$arr[] = $entry;
}
http://php.net/manual/en/function.readdir.php
But glob is better, now it only returns images.

Related

How to search file in folder by using php?

I have a folder called allfiles, and there are some files in this folder, such as
1212-how-to-sddk-thosd.html
3454-go-to-dlkkl-sdf.html
0987-sfda-asf-fdf-12331.html
4789-how-to-fdaaf-65536.html
I use scandir to list all files, and now I need to find the file by with keywords, example to-dlkkl is the keyword, and I will get the file 3454-go-to-dlkkl-sdf.html.
Glob seems not work, and opendir and readdir are not work well, any ideas?
Use loop foreach and strpos function:
$files = scandir('allfiles');
foreach ($files as $file) {
if (strpos('to-dlkkl', $file) !== false) {
//file found
}
}
I wonder why glob() function not working for it?
The below code should work I guess,
$existing_dir = getcwd();
// path to dir
chdir( '/var/www/allfiles/' );
foreach( glob( '*to-dlkkl*.html' ) as $html_file ) {
echo $html_file . '<br />';
}
chdir( $existing_dir );
you can use strstr to get actual file
$allfiles = scandir('./');
foreach ($allfiles as $file) {
if (strstr($file, 'to-dlkkl')) {
echo "file found"; //do what you want
}
}
If You want to search specific file under directory then you can use preg_match() .
<?php
if ($handle = opendir('/var/www/html/j')) { // here add your directory
$keyword = "index.php"; // your keyword
while (false !== ($entry = readdir($handle))) {
// (preg_match('/\.txt$/', $entry)) {
if (preg_match('/'.$keyword.'/i', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}
?>

List with array only some formats files n folder and subdirectory php on Ubuntu Server

I need to list all files for example mp4 or avi in my folder /Files and relative subdirectories and after that insert into <a href={$filename}><\a> tag so I need a array i suppose.
I tried with find command but I receive a string and not a Array so I've to split the string and this isn't practical.
Any suggestion?
or use class RecursiveDirectoryIterator - For example :
$dir_iterator = new RecursiveDirectoryIterator(dirname(__FILE__));
$iterator = new RecursiveIteratorIterator($dir_iterator);
foreach ($iterator as $filename)
{
if (dirname($filename) != dirname(__FILE__))
{
if(is_file($filename)) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == 'mp4' )
{
print ''.basename($filename)."<br />";
}
}
}
}
<?php
$dir ="/Files";
$files = scandir($dir);
foreach($files as $file) {
$fullname = "/Files/" . $file;
echo '<a href='.$fullname.'>File</a>;
}
This should work for you.

Get filenames of images in a directory

What should be done to get titles (eg abc.jpg) of images from a folder/directory using PHP and storing them in an array.
For example:
a[0] = 'ac.jpg'
a[1] = 'zxy.gif'
etc.
I will be using the array in a slide show.
It's certainly possible. Have a look at the documentation for opendir and push every file to a result array. If you're using PHP5, have a look at DirectoryIterator. It is a much smoother and cleaner way to traverse the contents of a directory!
EDIT: Building on opendir:
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$images = array();
while (($file = readdir($dh)) !== false) {
if (!is_dir($dir.$file)) {
$images[] = $file;
}
}
closedir($dh);
print_r($images);
}
}
'scandir' does this:
$images = scandir($dir);
One liner :-
$arr = glob("*.{jpg,gif,png,bmp}", GLOB_BRACE)
glob in php - Find pathnames matching a pattern
<?php
//path to directory to scan
$directory = "../images/team/harry/";
//get all image files with a .jpg extension. This way you can add extension parser
$images = glob($directory . "{*.jpg,*.gif}", GLOB_BRACE);
$listImages=array();
foreach($images as $image){
$listImages=$image;
}
?>

Php read directory file

I have a script that goes through a directory that has 3 images
$imglist='';
$img_folder = "path to my image";
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, checks if are images and ads them to a list
while ($file = $imgs->read()) {
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";
}
closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist);
//display image
foreach($imglist as $image) {
echo '<img src="'.$img_folder.$image.'">';
}
but the problem that I am having is it display a 4th img with no image.. yet I only have 3 image in that folder.
There is no need to build a string of images and then explode that string into an array of images instead just add the images directly to an array as Radu mentioned.
Here is the corrected code:
$imglist = array();
$img_folder = "path to my image";
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, checks if are images and adds them to a list
while ($file = $imgs->read()) {
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file)){
$imglist[] = $file;
}
}
closedir($imgs->handle);
//display image
foreach($imglist as $image) {
echo '<img src="'.$img_folder.$image.'">';
}
You'll have a space at the end of the $imglist string, which explode() will turn into an empty element. Trim the string:
$imglist = explode(" ", trim($imglist));
Or better yet, just add them to the $imglist array in the first place, instead of making a string and exploding it:
$imglist = array();
/* ... */
$imglist[] = $file;
ereg() is deprecated. You'd probably be better off with:
chdir($img_folder);
$imgs = glob('*.jpg *.gif *.png');
foreach ($imgs as $img) {
echo "<img src=\"{$img_folder}/{$img}\">";
}
glob() does wildcard matching pretty much the same way as most Unix shells do.
Use [glob()][1] function
<?php
define('IMAGEPATH', 'path to my image/'.$imglist.'/');
foreach(glob(IMAGEPATH.'*.jpg') as $filename){
echo '<img src="'.$filename.'" alt="'.$album.'" />';
?>
[1]: http://www.php.net/manual/en/function.glob.php

Display contents of multiple text files

I have a number of text files held in directory
/results/...
All the text files are named with unixtime stamps, inside each of the following files there is:
#text¬test¬test1¬test2¬test3¬test4¬1262384177
Each piece of text is seperated by '¬'.
I'd then like to feed the contents of the text file into an array and output it, in for example a table, but for each of the files (Perhaps loop-like?)
If have this but it only works for one file and fixed file name:
$filename = "results/unixtime.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$array01 = explode("¬",$contents);
$count = count($array01);
echo "<table width = 500 border=1 cellpadding=4>";
$i=0;
for ($i=0;$i<$count;$i++) {
echo "<tr><td>";
echo $array01[$i];
echo "</td></tr>";
}
echo "</table>";
I suggest the fairly-unknown glob function to detect all your files. Then with all the filenames in a handy array, just iterate through and open up/read each one. Sort of like this:
$files = glob('*.txt');
while(list($i, $filename) = each($files)){
//what you have now
}
A couple of things:
Unless you're dealing with really large files just use file_get_contents() to load files. It's a one-liner versus three lines of code that you just don't need;
Loop over arrays using foreach unless you explicitly need a loop counter. The loop condnition/counter is just another area where you can make simple errors;
Use opendir(), readdir() and closedir() for reading directory contents; and
Directories will contain entries like "." and "..". Use filetype() and/or a check on the name and/or extension to limit it to the files you're interested in.
Example:
$directory = "results/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
$items = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
foreach ($items as $item) {
echo "<tr><td>$item</td></tr>\n";
}
echo '</table>';
}
}
closedir($dir);
You can get all the files located in "result" via opendir.
There is also an example ...
<?php
$dir = "/etc/php5/";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
Grab the files in the directory and read each filename.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$filename = $file;
//your code
}
}
closedir($handle);
}
?>
source: http://php.net/manual/en/function.readdir.php
Here is a more elegant way of writing brianreavis solution, also use file_get_contents instead of fopen, fread and fclose, it's faster and less verbose.
foreach (glob('*.txt') as $filename)
{
$contents = file_get_contents($filename);
}
Use this code, replace DOCROOT with directory you want to scan.
foreach (scandir(DOCROOT.'css') as $dir) {
echo $dir . "<br>";
echo file_get_contents(DOCROOT . 'css/' . $dir ) . "<hr />";
}

Categories