read files from an array in php - php

I'm trying to open a directory, read just files with a .txt format and then display the contents. I've coded it out, but it doesn't do anything, although it doesn't register any errors either. Any help?
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
$entry=array();
while(false!==($file = readdir($handle))) {
if ( !strcmp($file, ".") || !strcmp($file, "..")) {
}
else if(substr($file, -4) == '.txt') {
$entry[] = $file;
}
foreach ($entry as $txt_file) {
if(is_file($txt_file) && is_writable($txt_file)) {
$file_open = fopen($txt_file, 'r');
while (!feof($file_open)) {
echo"<p>$file_open</p>";
}
}
}
}

Help is quite simple.
Instead
$dir = 'information';
If (is_dir($dir)) {
$handle = opendir($dir);
} else {
echo "<p>There is a system error</p>";
}
write (I am sorry for re-formatting of new lines)
$dir = 'information';
if(is_dir($dir))
{
$handle = opendir($dir);
}
else
{
echo "<p>There is a system error</p>";
}
because if has to be written only smallcaps, thus not If.
And the second part rewrite to (again, you may use your own formatting of new lines)
$entry=array();
$file = readdir($handle);
while($file !== false)
{
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
foreach ($entry as $txt_file)
{
if(is_file($txt_file) && is_writable($txt_file))
{
$file_open = fopen($txt_file, 'r');
while(!feof($file_open))
{
echo"<p>$file_open</p>";
}
}
}
}
because PHP has elseif, not else if like JavaScript. Also I separated $file = readdir($handle) for possible source of error.
Code part
if(!strcmp($file, ".") || !strcmp($file, ".."))
{
}
elseif(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
should be shortened only to
if(substr($file, -4) == '.txt')
{
$entry[] = $file;
}
because when if part is empty, then it is not neccessary.
That is all I can do for you at this time.

Instead of iterating the directory with readdir, consider using glob() instead. It allows you to specify a pattern and it returns all files that match it.
Secondly, your while loop has an error: you conditionally add the file name to the list of files, but then you always print every file name using a foreach loop. On the first loop it will print the first file. On the second loop it will print the first and second files, etc. You should separate your while and foreach loops to fix that issue (i.e. unnest them).
Using glob, the modified code will look like:
$file_list = glob('/path/to/files/*.txt');
foreach ($file_list as $file_name) {
if (is_file($file_name) && is_writable($file_name)) {
// Do something with $file_name
}
}

Related

Read file names from directory

I am trying to read and display all the files in a directory using this code.
It works fine for files in the same directory as the script. But when I try to display files in a folder (files/) it is giving me problems.
I've tried setting the directoy variable to many different things. like...
files/
files
/files/
etc... nothing seems to work. Does anyone have any idea why?
<?php
$dhandleFiles = opendir('files/');
$files = array();
if ($dhandleFiles) {
while (false !== ($fname = readdir($dhandleFiles))) {
if (is_file($fname) && ($fname != 'list.php') && ($fname != 'error.php') && ($fname != 'index.php')) {
$files[] = (is_dir("./$fname")) ? "{$fname}" : $fname;
}
}
closedir($dhandleFiles);
}
echo "Files";
echo "<ul>";
foreach ($files as $fname) {
echo "<li><a href='{$fname}'>{$fname}</a></li>";
}
echo "</ul>";
?>
You're not including the full path in your array:
while($fname = readdir($dhandleFiles)) {
$files[] = 'files/' . $fname;
^^^^^^^^---must include actual path
}
Remember that readdir() returns ONLY the filename, without path information.
This should help - take a look at SplFileInfo too.
<?php
class ExcludedFilesFilter extends FilterIterator {
protected
$excluded = array(
'list.php',
'error.php',
'index.php',
);
public function accept() {
$isFile = $this->current()->isFile();
$isExcluded = in_array($this->current(), $this->excluded);
return $isFile && ! $isExcluded;
}
}
$dir = new DirectoryIterator(realpath('.'));
foreach (new ExcludedFilesFilter($dir) as $file) {
printf("%s\n", $file->getRealpath());
}
How about using glob function.
<?php
define('MYBASEPATH' , 'files/');
foreach (glob(MYBASEPATH . '*.php') as $fname) {
if($fname != 'list.php' && $fname != 'error.php' && $fname != 'index.php') {
$files[] = $fname;
}
}
?>
read more about getting all files in directory here
This reads and prints filenames from a sub-directory:
$d = dir("myfiles");
while (false !== ($entry = $d->read())) {
if ($entry != ".") {
if ($entry != "..") {
print"$entry";
}
}
}
$d->close();

Control the order of the files with opendir() & readdir()

I checked at php.net opendir() but found no way to control the order of the files that opendir() gets.
I have a slideshow and I have problems controling the order of the images. I tried changing names and use 01.img,02.img,...,20.img but no sucess.
My script:
<?php
$path2 = "./img/";
function createDir($path2 = './img'){
if ($handle = opendir($path2)){
echo "<ul class=\"ad-thumb-list\">";
while (false !== ($file = readdir($handle))){
if (is_dir($path2.$file) && $file != '.' && $file !='..')
printSubDir($file, $path2, $queue);
else if ($file != '.' && $file !='..')
$queue[] = $file;
}
printQueue($queue, $path2);
echo "</ul>";
}
}
function printQueue($queue, $path2){
foreach ($queue as $file){
printFile($file, $path2);
}
}
function printFile($file, $path2){
if ($file=="thumbs.db") {echo "";}
else{
echo "<li><a href=\"".$path2.$file."\">";
echo "<img src=\"".$path2.$file."\" class='thumbnail'></a></li>";
}
}
/*function printSubDir($dir, $path2)
{
}*/
createDir($path2);
?>
Use scandir() and natsort().
Rewritten code:
function createDir($path2 = './img'){
$dirContents = scandir($path2);
natsort($dirContents);
echo "<ul class=\"ad-thumb-list\">";
// You should actually add the line below!
// $queue = array();
foreach ($dirContents as $entry) {
if ($entry == '.' || $entry == '..') {
continue;
}
$entryPath = $path2 . $entry;
if (is_dir($entryPath)) {
printSubDir($entry, $path2, $queue);
}
else {
$queue[] = $entry;
}
}
printQueue($queue, $path2);
echo "</ul>";
}
}
If you are using PHP 5, you could try using scandir() instead. It has an argument for sorting.
http://us1.php.net/scandir
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
As #Steven has already said, you may not be able to change the output of opendir(), but there's nothing stopping you from sorting the array afterwards.
To do this, have a look at the natsort() function, which is designed to properly sort strings like those you're using for file names.

A minor issue while iteration of array in php.Guidance please

I have several files in a directory.I want to display all those filenames with the extension .txt and .jpeg
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo("/etrade/home/collections/utils");
if (($actual_file["extension"]== "txt") ||
($actual_file["extension"]== "jpg") ||
($actual_file["extension"]== "pdf")) {
//Require changes here.Dont know how to iterate and get the list of files
echo "<td>"."\n"." $actual_file['basename']."</a></td>";
}
}
closedir($handle);
}
Please help me on how to iterate and get the list of files .For instance I want all files with jpg extension in a seperate column and pdf files in a seperate column(since I am going to display in a table)
See if this does what you want (EDITED):
<?php
$ignoreFiles = array('.','..'); // Items to ignore in the directory
$allowedExtensions = array('txt','jpg','pdf'); // File extensions to display
$files = array();
$max = 0;
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if (in_array($file, $ignoreFiles)) {
continue; // Skip items to ignore
}
// A simple(ish) way of getting a files extension
$extension = strtolower(array_pop($exploded = explode('.',$file)));
if (in_array($extension, $allowedExtensions)) { // Check if file extension is in allow list
$files[$extension][] = $file; // Create an array of each file type
if (count($files[$extension]) > $max) $max = count($files[$extension]); // Store the maximum column length
}
}
closedir($handle);
}
// Start the table
echo "<table>\n";
// Column headers
echo " <tr>\n";
foreach ($files as $extension => $data) {
echo " <th>$extension</th>\n";
}
echo " </tr>\n";
// Table data
for ($i = 0; $i < $max; $i++) {
echo " <tr>\n";
foreach ($files as $data) {
if (isset($data[$i])) {
echo " <td>$data[$i]</td>\n";
} else {
echo " <td />\n";
}
}
echo " </tr>\n";
}
// End the table
echo "</table>";
If you just want to display two lists of files (it's not clear what part you're having trouble with from your question) can't you just store the filenames in an array?
You don't seem to be getting the file details - you're getting the pathinfo for /etrade/home/collections/utils, but you never add the file name to it.
<?php
if ($handle = opendir("/home/work/collections/utils/")) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$actual_file=pathinfo($file);
switch ($actual_file['extension'])
{
case ('jpg'):
$jpegfiles[] = $actual_file;
break;
case ('pdf'):
$pdffiles[] = $actual_file;
break;
}
}
closedir($handle);
}
echo "JPG files:"
foreach($jpegfiles as $file)
{
echo $file['basename'];
}
echo "PDF Files:"
foreach($pdffiles as $file)
{
echo $file['basename'];
}
?>
Obviously you can be cleverer with the arrays, and have use multi-dimensional arrays and do away with the switch if you want.

delete multiple files from the folder

how can i delete multiple files from the folder?
code:$query=$this->main_model->get($id);
if($query->num_rows()>0)
{
foreach ($query->result() as $row)
{
unlink("uploads/".$id."/".$row->img_name);
unlink("uploads/".$id."/".$row->img_name_tn);
unlink("uploads/".$id."/".$row->file);
unlink("uploads/".$id."/".$row->file2);
unlink("uploads/".$id."/Thumbs.db");
}
rmdir("uploads/".$id);
}
here is the code i used but it delete the files at ones. and how can i delete all files from the folder?
originally from php.net:
<?php
$dir = '/uploads/';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") { // strip the current and previous directory items
unlink($dir . $file); // you can add some filters here, aswell, to filter datatypes, file, prefixes, suffixes, etc
}
}
closedir($handle);
}
?>
I found this at php.net:
"The shortest recursive delete possible"
function rrmdir($path) {
return is_file($path)?
#unlink($path):
array_map('rrmdir',glob($path.'/*'))==#rmdir($path)
;
}
You could do it like this:
function delete_files($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
}
}
closedir($dir_handle);
return true;
}
You need to use a recursive function. A comment from the rmdir page have written a function on how to do it, see http://www.php.net/manual/en/function.rmdir.php#98622. This code will delete the folder and everything in it.
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>

PHP - Check if a file exists in a folder

I wanna check if there any image on a folder from my server. I have this little function in PHP but is not working and I don't know why:
$path = 'folder/'.$id;
function check($path) {
if ($handle = opendir($path)) {
$array = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && count > 2) {
echo "folder not empty";
} else {
echo "folder empty";
}
}
}
closedir($handle);
}
Any help will be appreciated, thanks in advance.
It does not work because count is coming from nowhere. Try this instead:
$path = 'folder/'.$id;
function check($path) {
$files = glob($path.'/*');
echo empty($files) ? "$path is empty" : "$path is not empty";
}
Try this function: http://www.php.net/glob
Try This:
$path = 'folder/'.$id;
function check($path) {
if (is_dir($path)) {
$contents = scandir($path);
if(count($contents) > 2) {
echo "folder not empty";
} else {
echo "folder empty";
}
}
closedir($handle);
}
It counts the contents of the path. If there are more than two items, then its not empty. The two items we are ignoring are "." and "..".
Step 1: $query = select * from your_table where id=$id;
Step 2: $path=$query['path_column'];
Step 3: if($path!=null&&file_exit($path)&&$dir=opendir($path)){
while (($file = readdir($dir )) !== false)
{
if ($file == '.' || $file == '..')
{
continue;
}
if($file) // file get
{
$allowedExts = array("jpg");
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($extension, $allowedExts))
$file[]=$file;
}
$data[file_name'] = $file;
}
closedir($dir);
}

Categories