How to move repeated files from folder to another in php? - php

I want to scan my whatsapp images folder and move all the repeated images to folder named recycle bin to delete them later, here is my code:
<?php
$dir = 'C:\wamp\www\whatsapp';
$files = scandir($dir);
$x = 0;
foreach($files as $f1)
{
$crc1 = strtoupper(dechex(crc32(file_get_contents("whatsapp/".$f1))));
unset($files[$x]);
$j = 0;
foreach($files as $f2)
{
$crc2 = strtoupper(dechex(crc32(file_get_contents("whatsapp/".$f2))));
if($crc1 == $crc2){
rename("whatsapp/".$f2, "recycle bin/".$f2);
unset($files[$j]);
}
$j++;
}
$x++;
}
exit('Done');
does this code seems to be trusted to move only the repeated images without any mistakes?

I've write a small script for your case (but i have not tested its):
<?php
$fileHashes = [];
foreach(scandir('C:\wamp\www\whatsapp') as $file){
$fileHashes["whatsapp/".$file] = sha1(file_get_contents("whatsapp/".$file));
}
$doubles = array_diff_key($fileHashes, array_unique($fileHashes))
foreach($doubles as $file=>$hash){
unlink($file);
}
exit('Done');

Related

Loop throught directory and subdir

Pls sir, how can I loop through a directory and get the sub-directory name and all the files names so that I can generate a directory try, am trying to build a file manager in php.
I have tried:
$dir = new DirectoryIterator(dirname(FILE));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
You can scan a directory and display the name of files in it using the PHP Code below
<?php
$dir = 'dir/';
$files = scandir($dir);
$totFiles = sizeof($files);
for($i=2;$i<$totFiles;$i++){
$name = explode(".",$files[$i]);
echo "
$name[0]
";
}
?>

Open and read files in directory inside folder in PHP

Okay guys so I am a bit lost as to how to adjust my code. Up to now, I have my code to read any Json file in a directory, parse it and put it in a table - works great since I was only using 1 JSON file per table row.
What I need to do now is the following, each IP address I have gives me 3 JSON files now that are placed into a folder with the IP address as its name. In my main directory I will have many folder each with 3 JSON files in it.
I want to read each file in every folder, place the info I parse in a table and then move on to the next folder as a new row and do the same.
FOR REFERENCE::
Current file layout:
FOLDER-->JSON
-->JSON
-->JSON
New file layout:
FOLDER-->IPADDRESS-->JSONFILE1
-->JSONFILE2
-->JSONFILE3
-->IPADDRESS2-->JSONFILE1
--JSONFILE2
-->JSONFILE3
Current code for reading any JSON file in a directory:
$dir = "my dir";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
foreach(glob("*_name.json") as $filename) {
$data = file_get_contents($filename);
$testing = json_decode($data, true);
echo "<tr>";
echo "<td>{$filename }</td>";
foreach($testing[0] as $row) {
// code for parsing here ...
}
}
}
}
here you go using RecursiveIteratorIterator Class
function Get_Files()
{
$dir = "my_dir";
$init = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
$files = array();
foreach ($init as $file) {
if ($file->isDir()) {
continue;
}
$files[] = $file->getPathname();
}
return $files;
}
foreach (Get_Files() as $file) {
$data = file_get_contents($file);
$testing = json_decode($data, true);
echo "<tr>";
echo "<td>{$file}</td></tr>";
}
output:
my_dir\192.168.0.1\JSONFILE1.json
my_dir\192.168.0.1\JSONFILE2.json

php - Get the last modified dir

A little stuck on this and hoping for some help. I'm trying to get the last modified dir from a path in a string. I know there is a function called "is_dir" and I've done some research but can't seem to get anything to work.
I don't have any code i'm sorry.
<?php
$path = '../../images/';
// echo out the last modified dir from inside the "images" folder
?>
For example: The path variable above has 5 sub folders inside the "images" dir currently right now. I want to echo out "sub5" - which is the last modified folder.
You can use scandir() instead of is_dir() function to do it.
Here is an example.
function GetFilesAndFolder($Directory) {
/*Which file want to be escaped, Just add to this array*/
$EscapedFiles = [
'.',
'..'
];
$FilesAndFolders = [];
/*Scan Files and Directory*/
$FilesAndDirectoryList = scandir($Directory);
foreach ($FilesAndDirectoryList as $SingleFile) {
if (in_array($SingleFile, $EscapedFiles)){
continue;
}
/*Store the Files with Modification Time to an Array*/
$FilesAndFolders[$SingleFile] = filemtime($Directory . '/' . $SingleFile);
}
/*Sort the result as your needs*/
arsort($FilesAndFolders);
$FilesAndFolders = array_keys($FilesAndFolders);
return ($FilesAndFolders) ? $FilesAndFolders : false;
}
$data = GetFilesAndFolder('../../images/');
var_dump($data);
From above example the last modified Files or Folders will show as Ascending order.
You can also separate your files and folder by checking is_dir() function and store the result in 2 different arrays like $FilesArray=[] and $FolderArray=[].
Details about filemtime() scandir() arsort()
Here's one way you can accomplish this:
<?php
// Get an array of all files in the current directory.
// Edit to use whatever location you need
$dir = scandir(__DIR__);
$newest_file = null;
$mdate = null;
// Loop over files in directory and if it is a subdirectory and
// its modified time is greater than $mdate, set that as the current
// file.
foreach ($dir as $file) {
// Skip current directory and parent directory
if ($file == '.' || $file == '..') {
continue;
}
if (is_dir(__DIR__.'/'.$file)) {
if (filemtime(__DIR__.'/'.$file) > $mdate) {
$newest_file = __DIR__.'/'.$file;
$mdate = filemtime(__DIR__.'/'.$file);
}
}
}
echo $newest_file;
This will work too just like the other answers. Thanks everyone for the help!
<?php
// get the last created/modified directory
$path = "images/";
$latest_ctime = 0;
$latest_dir = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
if(is_dir($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_dir = $entry;
}
} //end loop
echo $latest_dir;
?>

PHP File count inside a folder

I'm using bootstrap tables and rows to count how much files are in a folder, but the destination is pointing to a different server the code below does not work.
As i'm using localhost (xampp) trying to do this don't know if its possible.
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/'; <!--\\189.207.00.122\folder1\folder2\folder3\test-->
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
Here is a handy little function you might want to try out. Just pass the path to the Directory as the first argument to it and you'd get your result.
NOTE: This Function is RECURSIVE, which means: it will traverse all sub-directories... to disable this behaviour, simply comment out or delete the following lines towards the end of the Funciton:
<?php
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
THE CODE:
<?php
$folder = dirname(__FILE__).'/uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS IN THE SAME DIRECTORY AS index.php
// (/htdocs/php/pages)
// OR
$folder = dirname(__FILE__).'/../uploads'; // ASSUMES YOUR uploads DIRECTORY
// IS ONE DIRECTORY ABOVE
// THE CURRENT DIRECTORY (/htdocs/php)
// THIS IS MOST LIKELY RIGHT
// OR
$folder = dirname(__FILE__).'/../../uploads';// ASSUMES YOUR uploads DIRECTORY
// IS TWO DIRECTORIES ABOVE
// THE CURRENT DIRECTORY (/htdocs)
// MAKE SURE THE FOLDER IN QUESTION HAS THE RIGHT PERMISSIONS
// OR RATHER CHANGE PERMISSIONS ON THE FOLDER TO BE ABLE TO WORK WITH IT
chmod($folder, 0777);
var_dump(getFilesInFolder($folder));
// IF YOU PASS false AS THE THE 2ND ARGUMENT TO THIS FUNCTION
// YOU'D GET AN ARRAY OF ALL FILES IN THE $path2Folder DIRECTORY
// AS WELL AS IN SUB-DIRECTORIES WITHIN IT...
function getFilesInFolder($path2Folder, $countOnly=true){
$files_in_dir = scandir($path2Folder);
$returnable = array();
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $path2Folder . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && !preg_match("#^\..*#", $temp_file_or_dir)){
$arrRX = array('#\.{2,4}$#', '#\.#');
$arrReplace = array("", "_");
$returnVal = preg_replace($arrRX, $arrReplace, $val);
$returnable[$returnVal] = $temp_file_or_dir;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return ($countOnly) ? count($returnable) : $returnable;
}
Use $_SERVER['DOCUMENT_ROOT'] to get your root directory.
$dir = $_SERVER['DOCUMENT_ROOT'].'/uploads/';

php rename behaving weird?

i have this script which i will post absolutely unmodified:
<?
chdir("data");
$files = glob("*");
shuffle($files);
var_dump($files);
$i=0;
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach($files as $file) {
$i++;
$k = $i;
$mime = finfo_file($finfo, $file);
if(strpos($mime,"gif") !== false) {
$ext = "gif";
} else {
$ext = "jpg";
}
if($k < 10) {
$k = "00".$k;
} else if($k < 100) {
$k = "0".$k;
}
$k = $k.".".$ext;
rename($file,$k);
echo $k."\n";
}
the folder data has some image files (jpg and gif) in it.
but when i run it, suddenly a lot of images are just gone!
2/3rd of the images just got deleted...
i don't understand how?
i have an ext3 filesystem and PHP 5.3.2
I can't see anything in the code that would definately cause this behaviour. The most likely cause I could think of is perhaps rename($file,$k); is overwriting files that already exist. You could add the following to rule this out:
if(file_exists($k.".".$ext)) {
$k .= ".0" ;
}
while(file_exists($k.".".$ext)) {
$k .= "0" ;
}
$k = $k.".".$ext;
rename($file,$k);
The other thought I had is that perhaps something is going wrong with the chdir("data") which you could check by inserting the full path before $file and $k when calling the rename. I don't think this is very likely though.
Did you run it twice?
The first time you run it it renames all the images to 0001.jpg - 00nn.jpg. The second time it starts overwriting stuff, because the source names and target names would overlap, e.g. it renames 0042.jpg to 0001.jpg, so the existing 0001.jpg disappears.
Would be good to check if $k exists before renaming $file to $k:
if(!is_file($k)) {
rename($file, $k);
}

Categories