loop through the files in a folder in php - php

i have searched through the Internet and found the scrip to do this but am having some problems to read the file names.
here is the code
$dir = "folder/*";
foreach(glob($dir) as $file)
{
echo $file.'</br>';
}
this display in this format
folder/s0101.htm
folder/s0692.htm
for some reasons i want to get them in this form.
s0101.htm
s0692.htm
can anyone tell me how to do this?

Just use basename() wrapped around the $file variable.
<?php
$dir = "folder/*";
foreach(glob($dir) as $file)
{
if(!is_dir($file)) { echo basename($file)."\n";}
}
The above code ignores the directories and only gets you the filenames.

You can use pathinfo function to get file name from dir path
$dir = "folder/*";
foreach(glob($dir) as $file) {
$pathinfo = pathinfo($file);
echo $pathinfo['filename']; // as well as other data in array print_r($pathinfo);
}

Related

PHP move files with specific name

I have 100.000+ files with name RMA_(NUMBER)(DATE)(TIME).jpg like RMA_12345_2015_10_12_17_00_35.jpg
How I can move this file like RMA_35200_*.jpg?
You can use command:
$ mv RMA_35200_*.jpg new_path
or use php for that, example:
<?php
$fromPath = __DIR__ . '/from';
$toPath = __DIR__ . '/to';
$files = glob("{$fromPath}/RMA_35200_*.jpg");
foreach ($files as $file) {
$fileName = basename($file);
rename($file, "{$toPath}/{$fileName}");
}
Use glob()to find those files and rename() to move them
function moveFiles($source, $target) {
// add missing "/" after target
if(substr($target,-1) != '/') $target .= '/';
$files = glob($source);
foreach($files as $file) {
$info = pathinfo($file);
$destination = $target . $info['filename'];
rename($file, $destination);
}
}
moveFiles('/where/my/files/are/RMA_35200_*.jpg', '/where/they/should/be/';
I'd have to agree with the other comments, "Use glob()to find those files and rename() to move them", etc.
But, there's one thing I would add, a preg_match for the file name. PERL regular expression matching the file name. I think that's what you may be missing from these answers.
foreach ($files as $file) {
if (preg_match('/RMA_[0-9\-_]+.jpg/i', $file) {
...more code here...
}
}

PHP Remove all Files From a Directory - Exclude File Extension

I am trying for the life of me to find the best way to delete all files in a single directory excluding a single file extension, ie anything that is not .zip
The current method I have used so far which successfully deletes all files is:
$files = glob('./output/*');
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
I have tried modifying this like so:
$files = glob('./output/**.{!zip}', GLOB_BRACE);
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
However, I am not hitting the desired result. I have changed the line as follows which has deleted only the zip file itself (so I can do the opposite of desired).
$files = glob('./output/*.{zip}', GLOB_BRACE);
I understand that there are other methods to read directory contents and use strpos/preg_match etc to delete accordingly. I have also seen many other methods, but these seem to be quite long winded or intended for recursive directory loops.
I am certainly not married to glob(), I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
Any help/advice is appreciated.
$exclude = array("zip");
$files = glob("output/*");
foreach($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($extension, $exclude)) unlink($file);
}
This code works by having an array of excluded extensions, it loads up all files in a directory then checks for the extension of each file. If the extension is in the exclusion list then it doesn't get deleted. Else, it does.
This should work for you:
(I just use array_diff() to get all files which are different to *.zip and then i go through these files and unlink them)
<?php
$files = array_diff(glob("*.*"), glob("*.zip"));
foreach($files as $file) {
if(is_file($file))
unlink($file); // delete file
}
?>
How about calling to the shell? So in Linux:
$path = '/path/to/dir/';
$shell_command = escapeshellcmd('find ' . $path .' ! -name "*.zip" -exec rm -r {}');
$output = shell_exec($shell_command);
I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
SPL Iterators are very effective and efficient.
This is what I would use:
$folder = __DIR__;
$it = new FilesystemIterator($folder, FilesystemIterator::SKIP_DOTS);
foreach ($it as $file) {
if ($file->getExtension() !== 'zip') {
unlink($file->getFilename());
}
}
Have you tried this:
$path = "dir/";
$dir = dir($path);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && substr($file, -4) !== '.zip') {
unlink($file);
}
}

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.

Read only pdf files and get the filename of that pdf files in a directory

I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here

Get a list of files and filenames without an extention using php

I'm trying to make a jQuery slider that automatically loads all the images in a specified folder. So I'm using a small PHP script that makes a list of all the files in that directory. For the captions of the slider I wanted to use the filename (without extension).
I'm using the following script, using PHP. It can list all the files with the extensions, but I can't find a way to also display the filename (for the captions) without the extensions.
Anyone an idea?
Thanks in advance!
<?
$path = "img";
$dir_handle = #opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
continue;
echo "$file";
}
closedir($dir_handle);
?>
Here you have more OO way:
$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
$fileinfo->getBasename('.' .$fileinfo->getExtension());
}
}
You can get the filename without its extension using pathinfo():
$filename = pathinfo( $file, PATHINFO_FILENAME);

Categories