Wrong result of sizeof - php

I have several files in a folder and i want to count them.
$folder = "images";
$allPics = scandir($folder);
$result = sizeof($allPics);
echo $result;
The result is 350 but it should be 348. I don't get it why it is showing me the result +2?
Am i missing something?!

http://php.net/manual/en/function.scandir.php
When looking at the documentation you can see the function return both '.' and '..', that's why you're having 2 more than you should have.
You can use this:
array_diff(scandir($folder), array('..', '.'));
To get rid of the dots you don't wanna have.

You are using the unix system and it have, 2 pointers in each directory, the pointer for the parent dirrectory that usualy is notted with .. and the pointer to the current directory that is notted as .

Related

Php how to go one level down on dirname(__FILE__)?

with this code I get filename from the current folder
<?php
$mydir = dirname(__FILE__);
$myfiles = array_diff(scandir($mydir), array('.', '..'));
$arrsingleresult = str_replace('.php', '', $myfiles);
print_r($arrsingleresult);
?>
Now how can I get filenames from one folder back ? (../ like this) any work around ?
Please use double time dirname() function to back one level
dirname(dirname(__FILE__));

rename all files in folder with random name

I want to rename all files in a folder with random numbers or characters.
This my code:
$dir = opendir('2009111');
$i = 1;
// loop through all the files in the directory
while ( false !== ( $file = readdir($dir) ) ) {
// do the rename based on the current iteration
$newName = rand() . (pathinfo($file, PATHINFO_EXTENSION));
rename($file, $newName);
// increase for the next loop
$i++;
}
// close the directory handle
closedir($dir);
but I get this error:
Warning: rename(4 (2).jpg,8243.jpg): The system cannot find the file specified
You're looping through files in the directory 2009111/, but then you refer to them without the directory prefix in rename().
Something like this should work better (though see the warning about data loss below):
$oldName = '2009111/' . $file;
$newName = '2009111/' . rand() . (pathinfo($file, PATHINFO_EXTENSION));
rename($oldName, $newName);
Of course, you may want to put the directory name in a variable or make other similar tweaks. I'm still not clear on why you're trying to do this, and depending on your goals there may be better ways of reaching them.
Warning! The approach you are using could cause data loss! A $newName could be generated that is the same name as an existing file, and rename() overwrites target files.
You should probably make sure $newName doesn't exist before you rename().

Best way to get files from a dir filtered by certain extension in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
So right now I have a directory and I am getting a list of files
$dir_f = "whatever/random/";
$files = scandir($dir_f);
That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.
PHP has a great function to help you capture only the files you need. Its called glob()
glob - Find pathnames matching a pattern
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Here is an example usage -
$files = glob("/path/to/folder/*.txt");
This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.
Reference -
glob()
If you want more than one extension searched, then preg_grep() is an alternative for filtering:
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.
PHP's glob() function let's you specify a pattern to search for.
You can try using GlobIterator
$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);
glob($pattern, $flags)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
try this
//path to directory to scan
$directory = "../file/";
//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");
//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array
}
haven't tested the regex but something like this:
if ($handle = opendir('/file/path')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.txt$/', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}

How to reference the current directory name, filename and file contents with RecursiveDirectoryIterator loop?

In the script below, I'm attempting to iterate over the folders and files inside of the $base folder. I expect it to contain a single level of child folders, each containing a number of .txt files (and no subfolders).
I'm just needing to understand how to reference the elements in comments below...
Any help much appreciated. I'm really close to wrapping this up :-)
$base = dirname(__FILE__).'/widgets/';
$rdi = new RecursiveDirectoryIterator($base);
foreach(new RecursiveIteratorIterator($rdi) as $files_widgets)
{
if ($files_widgets->isFile())
{
$file_name_widget = $files_widgets->getFilename(); //what is the filename of the current el?
$widget_text = file_get_contents(???); //How do I reference the file here to obtain its contents?
$sidebar_id = $files_widgets->getBasename(); //what is the file's parent directory name?
}
}
//How do I reference the file here to obtain its contents?
$widget_text = file_get_contents(???);
$files_widgets is a SplFileInfo, so you have a few options to get the contents of the file.
The easiest way is to use file_get_contents, just like you are now. You can concatenate together the path and the filename:
$filename = $files_widgets->getPathname() . '/' . $files_widgets->getFilename();
$widget_text = file_get_contents($filename);
If you want to do something funny, you can also use openFile to get a SplFileObject. Annoyingly, SplFileObject doesn't have a quick way to get all of the file contents, so we have to build a loop:
$fo = $files_widgets->openFile('r');
$widget_text = '';
foreach($fo as $line)
$widget_text .= $line;
unset($fo);
This is a bit more verbose, as we have to loop over the SplFileObject to get the contents line-by-line. While this is an option, it'll be easier for you just to use file_get_contents.

PHP: Last file in directory

How do I get the name of the last file (alphabetically) in a directory with php? Thanks.
Using the Directories extension you can do it simply with
$all_files = scandir("/my/path",1);
$last_files = $all_files[0];
The scandir command returns an array with the list of files in a directory. The second parameter specifies the sort order (defaults to ascending, 1 for descending).
<?php
$dir = '/tmp';
$files = scandir($dir, 1);
$last_file = $files[0];
print($last_file);
?>
Code here looks like it would help - would just need to use end($array) to collect the last value in the generated array.
$files = scandir('path/to/dir');
sort($files, SORT_LOCALE_STRING);
array_pop($files);

Categories