remove files in directory not match array - php

I post array to php try to remove the file in directory but not in array.
Below code foreach can get the file name in array, while get all the files in directory.
I tried the function like below wrong one, put the while in foreach expect find the file not match $row then unlink. But it failed it will remove some files in array.. seems my logic was wrong. did I doing something wrong?
$dir = "img/";
foreach($img_arr as $row) {
print $row; // get : 2.png 3.png 0.png ....
}
$opendir = opendir($dir);
while ($file = readdir($opendir)) {
// if($file != $row && $file!="." && $file!=".."){
print $file; //get : ...2.png 3.png ...0.png ....
// }
}
wrong
$dir = "img/";
foreach($img_arr as $row) {
print $row; // get : 2.png 3.png 0.png ....
$opendir = opendir($dir);
while ($file = readdir($opendir)) {
if($file != $row && $file!="." && $file!=".."){
print $file; // expect get the file not match $row
}
}
}

Use in_array to check if file exists in your $img_arr:
$img_arr = array(.....); // here comes your array
$opendir = opendir($dir);
// don't forget to stop while-loop also
while (($file = readdir($opendir)) !== false) {
if($file!="." && $file!=".." && !in_array($file, $img_arr)){
print $file;
}
}

Related

read files from an array in 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
}
}

unique file names in php from dir

<?
if ($directory = opendir('data/')) { // Open dir
while (false !== ($files = readdir($directory))) { //Read directory
if ($files != "." && $files != "..") { //Strip . and ..
$files = str_replace("122.","",$files); // Remove 122.
$files = str_replace("234.","",$files); // Remove 234.
echo "$files<br />"; // Get results
}
}
closedir($directory); // close directory
}
?>
files in directory is: 122.256879, 234.4263, 122.4263, 234.256879
I get results:
256879
4263
4263
256879
But i need unique results:
256879
4263
How to get this results?
<?
$aFiles = array();
if ($directory = opendir('data/')) { // Open dir
while (false !== ($files = readdir($directory))) { //Read directory
if ($files != "." && $files != "..") { //Strip . and ..
$files = str_replace("122.","",$files); // Remove 122
$files = str_replace("234.","",$files); // Remove 234
if(in_array($files, $aFiles) == false){
echo "$files<br />"; // Get results
$aFiles[] = $files;
}
}
}
closedir($directory); // close directory
}
?>

How get first modified file in a folder using PHP?

How get first modified file?
So far I've had:
$dir = $path.'/';
$firstMod = '';
$p = 1;
foreach (scandir($dir) as $file) {
if (is_file($dir.$file) && ... ) {
if($p == 1) break;
}
}
If I would like to get last file but not last modified but last in an folder order what should I use?
you can try to write all the files in the array make key as the date modified than reorder the array based on date and get the first element of array which would first modified.
<?php
$folder = "files/";
$handle = opendir($folder);
$files=array();
while ($file = readdir($handle)){
if( $file != ".." && $file != "." ){
$key = filemtime($file);
$files[$key] = $file ;
}
}
closedir($handle);
ksort($files) ;
echo reset($files);
?>

Rename all files in a directory with numbers

I was wondering if anyone could help me write a PHP script for me that renames all the files in a directory in a sequence.
So...
DSC_10342.JPG -> 1.JPG
DSC_10343.JPG -> 2.JPG
DSC_10344.JPG -> 3.JPG
and so on.
Here's my version:
// open the current directory (change this to modify where you're looking)
$dir = opendir('.');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.jpg'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
{
// do the rename based on the current iteration
$newName = $i . '.jpg';
rename($file, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
Use rename to rename the files. You can use this handy script to loop through all files in a directory:
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Then it's just a matter of looking at the filenames ($file) and figuring out what number to give them. If you need more help than that, just tell me and I'll give more details.
Try this:
$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
rename($directory."/".$file, $directory."/".$index.".JPG");
$index++;
}
}
closedir($handler);
Using someone's snippet it would look like this:
<?php
$path = '.';
$i = 1;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && is_file($path.'/'.$file)) {
$oldname = $path.'/'.$file;
$path_info = pathinfo($oldname);
rename($oldname, $path.'/'.($i++).'.'.$path_info['extension']);
}
}
closedir($handle);
}
?>
It will rename files with all extensions and skip directories that may be inside your directory.

PHP - Code to traverse a directory and get all the files(images)

i want to write a page that will traverse a specified directory.... and get all the files in that directory...
in my case the directory will only contain images and display the images with their links...
something like this
How to Do it
p.s. the directory will not be user input.. it will be same directory always...
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
use readdir
<?php
//define directory
$dir = "images/";
//open directory
if ($opendir = opendir($dir)){
//read directory
while(($file = readdir($opendir))!= FALSE ){
if($file!="." && $file!= ".."){
echo "<img src='$dir/$file' width='80' height='90'><br />";
}
}
}
?>
source: phpacademy.org
You'll want to use the scandir function to walk the list of files in the directory.
Hi you can use DirectoryIterator
try {
$dir = './';
/* #var $Item DirectoryIterator */
foreach (new DirectoryIterator($dir) as $Item) {
if($Item->isFile()) {
echo $Item->getFilename() . "\n";
}
}
} catch (Exception $e) {
echo 'No files Found!<br />';
}
If you want to pass directories recursively:
http://php.net/manual/en/class.recursivedirectoryiterator.php
/**
* function get files
* #param $path string = path to fine files in
* #param $accept array = array of extensions to accept
* #param currentLevel = 0, stopLevel = 0
* #return array of madmanFile objects, but you can modify it to
* return whatever suits your needs.
*/
public static function getFiles( $path = '.', $accept, $currentLevel = 0, $stopLevel = 0){
$path = trim($path); //trim whitespcae if any
if(substr($path,-1)=='/'){$path = substr($path,0,-1);} //cutoff the last "/" on path if provided
$selectedFiles = array();
try{
//ignore these files/folders
$ignoreRegexp = "/\.(T|t)rash/";
$ignore = array( 'cgi-bin', '.', '..', '.svn');
$dh = #opendir( $path );
//Loop through the directory
while( false !== ( $file = readdir( $dh ) ) ){
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) and !preg_match($ignoreRegexp,$file)){
$spaces = str_repeat( ' ', ( $currentLevel * 4 ) );
// Its a directory, so we need to keep reading down...
if( is_dir( "$path/$file" ) ){
//merge current selectFiles array with recursion return which is
//another array of selectedFiles
$selectedFiles = array_merge($selectedFiles,MadmanFileManager::getFiles( "$path/$file", $accept, ($currentLe$
} else{
$info = pathinfo($file);
if(in_array($info['extension'], $accept)){
$selectedFiles[] = new MadmanFile($info['filename'], $info['extension'], MadmanFileManager::getSize($
}//end if in array
}//end if/else is_dir
}
}//end while
closedir( $dh );
// Close the directory handle
}catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
return $selectedFiles;
}
You could as others have suggested check every file in the dir, or you could use glob to identify files based on extension.
I use something along the lines of:
if ($dir = dir('images'))
{
while(false !== ($file = $dir->read()))
{
if (!is_dir($file) && $file !== '.' && $file !== '..' && (substr($file, -3) === 'jpg' || substr($file, -3) === 'png' || substr($file, -3) === 'gif'))
{
// do stuff with the images
}
}
}
else { echo "Could not open directory"; }
You could also try the glob function:
$path = '/your/path/';
$pattern = '*.{gif,jpg,jpeg,png}';
$images = glob($path . $pattern, GLOB_BRACE);
print_r($images);
$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);
}
}
For further reference :http://php.net/manual/en/function.opendir.php
I would start off by creating a recursive function:
function recurseDir ($dir) {
// open the provided directory
if ($handle = opendir($_SERVER['DOCUMENT_ROOT'].$dir)) {
// we dont want the directory we are in or the parent directory
if ($entry !== "." && $entry !== "..") {
// recursively call the function, if we find a directory
if (is_dir($_SERVER['DOCUMENT_ROOT'].$dir.$entry)) {
recurseDir($dir.$entry);
}
else {
// else we dont find a directory, in which case we have a file
// now we can output anything we want here for each file
// in your case we want to output all the images with the path under it
echo "<img src='".$dir.$entry."'>";
echo "<div><a href='".$dir.$entry."'>".$dir.$entry."</a></div>";
}
}
}
}
The $dir param needs to be in the following format:
"/path/" or "/path/to/files/"
Basically, just don't include the server root, because i have already done that below using $_SERVER['DOCUMENT_ROOT'].
So, in the end just call the recurseDir function we just made in your code once, and it will traverse any sub folders and output the image with the link under it.

Categories