PHP Scandir returns extra periods - php

So I am trying to build a script that scans a directory and returns random images to be used as backgrounds.
The php looks like this:
$dir = "views/img/bg/";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$random_key = array_rand($files, 1);
$random = $files[$random_key];
Then I am just using some simple jquery to attach the images as backgrounds:
<script>
$(document).ready(function(){
$("body").css( "background" , "url(http://'.$url_root.'/views/img/bg/'.$random.'), center center" );
});
</script>
Everything works fine but the array of all the images in the background folder seems to be returning stuff like '.' or '..' instead of image names every once in a while. Im not sure what is going on - any ideas?

Use glob() so you can filter the files.
$files = glob('views/img/bg/*.jpg');
$random = $files[array_rand($files)];
Since you're specifying *.jpg, $files contains only JPG files and you don't need to remove the . and .. items.

'.' and '..' are returned for current and parent directory. You can filter them:
while (false !== ($filename = readdir($dh))) {
if ($filename != '.' && $filename != '..')
$files[] = $filename;
}

Why not use regex? That way it captures any amount of periods. (i.e. ".", "..", "..." etc..)
while (false !== ($filename = readdir($dh))) {
if(!preg_match('/^\.*$/',$filename)){
$files[] = $filename;
}

$dh = opendir("c:\");
while (false !== ($filename = readdir($dh))) {
if ($filename != '.' && $filename != '..')
$files[] = $filename;
}

Related

How to delete file in PHP

I want to delete files in a specific directory in PHP. How can I achieve this?
I have the following code but it does not delete the files.
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
I think your question isn't specific, this code must clear all files in the directory 'files'.
But there are some errors in that code I think, and here is the right code:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
And finally make sure that you provided the right path to dir().
You can get all directory contents with glob and check if the value is a file with is_file() before unlinking it.
$files = glob('files/*'); // get directory contents
foreach ($files as $file) { // iterate files
// Check if file
if (is_file($file)) {
unlink($file); // delete file
}
}
If you want to remove files matching a pattern like .png or .jpg, you have to use
$files = glob('/tmp/*.{png,jpg}', GLOB_BRACE);
See manual for glob.

Get images url from folder Filter only images from folder

I use the code suggested here
https://stackoverflow.com/a/18316453
This is what I have now.
<?php
$dir = "sliders/slides";
$images = array();
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
if (!is_dir($dir.$file)) $images[] = $dir . '/' . $file;
}
closedir($dh);
}
}
echo json_encode($images);
?>
My result includes 2 extra items
sliders/slides/.
sliders/slides/..
which makes my slider having 2 extra blank slides
How can I filter the result to show only .jpg and .png files in order to remove /. and /.. be included in the results
I'm trying to create sliders that gets images from a folder
Thanks
Try something like this inside the while :
if ($file != "." && $file != ".." && !is_dir($file) {
$images[] = $dir . '/' . $file;
}

Unable to rename all the files in a folder

I've been trying to change the file extension of all the picture files in a folder using the following snippet:
$dh = opendir('JS2C');
$files = array();
while (($file = readdir($dh)) !== false) {
if($file !== '.' && $file !== '..') {
$file = pathinfo($file);
rename($file, $new . '.jpg');
}
}
I get the following warning messages:
SCREAM: Error suppression ignored for
Warning: rename(ANAZODO.gif,ANAZODO.jpg):
The system cannot find the file specified. (code: 2) in C:\wamp2\www\ckcportal\batch2.php on ...
The folder that contains the files is in the same folder with the PHP script.
you are missing directory for rename
$d = 'JS2C/'
$dh = opendir($d);
while (($file = readdir($dh)) !== false) {
if($file !== '.' && $file !== '..') {
//$file_no_ext = substr($file, 0,strrpos($file,'.'));// before php 5.2
$path_parts = pathinfo($file); // php 5.2
$file_no_ext = $path_parts['filename']; // php 5.2
rename($d.$file, $d.$file_no_ext . '.jpg');
}
}
You have to supply the full path, from the error you are receiving, it looks like you are just giving the file name.
rename('/path/to/old/file', '/path/to/new/file');
And why are you using $file = pathinfo($file);? pathinfo creates an assoc. array from information of $file which should be giving you the full path. If you take this out, it should work.
Unless you need to following:
$info = pathinfo($file);
$path = $info['dirname']
$new_file = $path . '/' . 'newfile.ext';
rename($file, $new_file);

PHP: How to list files in a directory without listing subdirectories

This is the starting portion of my code to list files in a directory:
$files = scandir($dir);
$array = array();
foreach($files as $file)
{
if($file != '.' && $file != '..' && !is_dir($file)){
....
I'm trying to list all files in a directory without listing subfolders. The code is working, but showing both files and folders. I added !is_dir($file) as you see in my code above, but the results are still the same.
It should be like this, I think:
$files = scandir($dir);
foreach($files as $file)
{
if(is_file($dir.$file)){
....
Just use is_file.
Example:
foreach($files as $file)
{
if( is_file($file) )
{
// Something
}
}
This will scan the files then check if . or .. is in an array. Then push the files excluding . and .. in the new files[] array.
Try this:
$scannedFiles = scandir($fullPath);
$files = [];
foreach ($scannedFiles as $file) {
if (!in_array(trim($file), ['.', '..'])) {
$files[] = $file;
}
}
What a pain for something so seemingly simple! Nothing worked for me...
To get a result I assumed the file name had an extension which it must in my case.
if ($handle = opendir($opendir)) {
while (false !== ($entry = readdir($handle))) {
$pos = strpos( $entry, '.' );
if ($entry != "." && $entry != ".." && is_numeric($pos) ) {
............ good entry
Use the DIRECTORY_SEPARATOR constant to append the file to its directory path too.
function getFileNames($directoryPath) {
$fileNames = [];
$contents = scandir($directoryPath);
foreach($contents as $content) {
if(is_file($directoryPath . DIRECTORY_SEPARATOR . $content)) {
array_push($fileNames, $content);
}
}
return $fileNames;
}
This is a quick and simple one liner to list ONLY files. Since the user wants to list only files, there is no need to scan the directory and return all the contents and exclude the directories. Just get the files of any type or specific type. Use * to return all files regardless of extension or get files with a specific extension by replacing the * with the extension.
Get all files regardless of extension:
$files = glob($dir . DIRECTORY_SEPARATOR . "*");
Get all files with the php extension:
$files = glob($dir . DIRECTORY_SEPARATOR . "*.php");
Get all files with the js extension:
$files = glob($dir . DIRECTORY_SEPARATOR . "*.js");
I use the following for my sites:
function fileList(string $directory, string $extension="") :array
{
$filetype = '*';
if(!empty($extension) && mb_substr($extension, 0, 1, "UTF-8") != '.'):
$filetype .= '.' . $extension;
else:
$filetype .= $extension;
endif;
return glob($directory . DIRECTORY_SEPARATOR . $filetype);
}
Usage :
$files = fileList($configData->includesDirectory, '');
With my custom function, I can include an extension or leave it empty. Additionally, I can forget to place the . before the extension and it will succeed.

is_dir does not recognize folders

I am trying to make a function that scans a folder for subfolders and then returns
a numeric array with the names of those folders.
This is the code i use for testing. Once i get it to print out the folder names and not just "." and ".." for present and above folder all will be well, and I can finish the function.
<?php
function super_l_getthemes($dir="themes")
{
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
closedir($handle);
}
?>
The above code works fine, and prints out all the contents of the folder: files, subfolders and the "." and ".."
but if i replace:
while (false !== ($file = readdir($handle))) {
echo "{$file}<br>";
}
with:
while (false !== ($file = readdir($handle))) {
if(file_exists($file) && is_dir($file)){echo "{$file}";}
}
The function only prints "." and ".." , not the two folder names that I'd like it to print.
Any help is appreciated.
You must provide the absolute path to file_exists, otherwise it will look for it in the current execution path.
while (false !== ($file = readdir($handle))) {
$file_path = $dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($file_path) && is_dir($file_path)) {
echo "{$file}";
}
}
The problem with readdir is that it only reads the strings of the named entries inside of the directory.
For instance, if you had file "foo" inside of directory "/path/to/files/", when using readdir on "/path/to/files/", you would eventually come to the string "foo".
Normally this wouldn't be a problem if it were in the same directory as the current working directory of the script, but, since you are reading from an arbitrary director, when you are attempting to inspect the entry (file, directory, whatever), you are calling is_dir on the bare string "foo".
I would try prefixing the name you pull out using readdir with the path to the file.
if ($handle = opendir($dir)) {
echo "Handle: {$handle}\n";
echo "Files:\n";
while ($file = readdir($handle)) {
/*** make $file into an absolute path ***/
$absolute_path = $dir . '/' . $file;
/*** NOW try stat'ing it ***/
if (is_dir($absolute_path)) {
/* it's a directory; do stuff */
}
}
closedir($handle);
}
You need to use:
while (false !== ($file = readdir($handle))) {
if(file_exists($dir.'/'.$file) && is_dir($dir.'/'.$file)){echo "{$file}";}
}
See http://php.net/readdir
If you only want the directories of the starting folder, you can simply do:
glob('/some/path/to/search/in/*', GLOB_ONLYDIR);
which would given you only those foldernames in an array. If you want all directories below a given path, try SPL's RecursiveDirectoryIterator
$fileSystemIterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/some/path/to/look/in'),
RecursiveIteratorIterator::SELF_FIRST);
Iterators can be used with foreach:
$directories = array();
foreach($fileSystemIterator as $path => $fileSystemObject) {
if($fileSystemObject->isDir()) {
$directories[] = $path;
}
}
You will then have an array $directories with all directories under the given path.
$files = array();
foreach(new DirectoryIteraror('/path') as $file){
if($file->isDir() /* && !$file->isDot()*/) $files[] = $file->getFilename();
}
[edit: though you wanted to skip the dot, commented it out)
I don't think you need both file_exists and is_dir,
You just need the is_dir function. From the manual:
is_dir Returns TRUE if the filename exists and is a directory, FALSE otherwise.
Use this:
while (false !== ($file = readdir($handle))) {
if(is_dir($file)){echo "{$file}";}
}
is_dir will also check whether it's a relative path or an absolute path.
$directory = scandir($path);
foreach($directory as $a){
if(is_dir($path.$a.'/') && $a != '.' && $a != '..'){
echo $a.'<br/>';
}
}
With the path given as shown, it displays the folders present in the path.
I agree with nuqqsa's solution, however, I'd like to add something to it.
Instead of specifying the path, you can change the current directory instead.
For example,
// open directory handle
// ....
chdir($dir);
while (false !== ($file = readdir($handle)))
if(is_dir($file))
echo $file;
// close directory handle

Categories