I have the following files:
1.jpg
2.jpg
3.jpg
4.jpg
When I remove 2.jpg, I want 3.jpg to become 2.jpg and 4.jpg to become 3.jpg
I tried a for loop with the rename function, but it does not seem to work:
for($a = $i;$a < $filecount;$a ++)
{
rename('photo/'.($a+1).'.jpg', 'photo/'. ($a).'.jpg');
}
Where $i is the number of the photo I just deleted.
List all files, sorted by name:
$files = glob('../photos/*');
Foreach file, rename it if necessary:
foreach($files as $i => $name) {
$newname = sprintf('../photos/%d.jpg', $i+1);
if ($newname != $name) {
rename($name, $newname);
}
}
Why don't you just remove the file you don't longer need and than rename all files that remain in the folder, starting with one. Like:
<?php
$fileToRemove= '3.jpg';
unlink($fileToRemove);
$cnt = 0;
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
rename($file, ++$cnt+".jpg");
}
}
closedir($handle);
}
?>
This way, you are always sure that the sequence is correct. If you have a lot of files, you can of cource start renaming from the number of the file you are deleting.
I would have do it this way:
echo "<pre>";
$files = array('file1.jpg', 'file5.jpg', 'file7.jpg', 'file9.jpg');
function removeElement($array, $id){
$clone = $array; // we clone the array for naming usage
$return = array(); // the array returned for testing purposes
$j = 0;
foreach($array as $num => $file){ // loop in the elements
if($file != $id){ // check if the current file is not the element we want to remove
if($num == $j){ // if current element and '$j' are the same we do not need to rename that file
$return[] = "// #rename('".$file."', '".$file."'); -- do not rename";
} else { // if previously we have removed the file '$id' then '$j' should be -1 and we rename the file with the next one stored in '$clone' array
$return[] = "#rename('".$file."', '".$clone[($num-1)]."'); // rename";
}
} else { // this is for the file we need to remove, we also -1 current '$j'
$j--;
}
$j++;
}
return $return;
}
print_r(removeElement($files, 'file5.jpg'));
it seems rudimentary, but it works and is easy to read.
$filecount = 5;
$i = 2;
unlink('photo/'. $i . '.jpg');
for($i; $i < $filecount; $i++) {
rename('photo/'. ($i+1) .'.jpg', 'photo/'. $i . '.jpg');
}
die;
Related
I want to keep only 10 newest files in a folder and delete others.
I created a script that deletes only the oldest ones if a file number is larger than 10.
How can I adapt this script to my needs?
$directory = "/home/dir";
// Returns array of files
$files = scandir($directory);
// Count number of files and store them to variable..
$num_files = count($files)-2;
if($num_files>10){
$smallest_time=INF;
$oldest_file='';
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
$time=filemtime($directory.'/'.$file);
if (is_file($directory.'/'.$file)) {
if ($time < $smallest_time) {
$oldest_file = $file;
$smallest_time = $time;
}
}
}
closedir($handle);
}
echo $oldest_file;
unlink($oldest_file);
}
Basic script to give you the idea. Push all the files with their times into an array, sort it by descending time order and walk trough. if($count > 10) says when the deletion should start, i.e. currently it keeps the newest 10.
<?php
$directory = ".";
$files = array();
foreach(scandir($directory) as $file){
if(is_file($file)) {
//get all the files
$files[$file] = filemtime($file);
}
}
//sort descending by filemtime;
arsort($files);
$count = 1;
foreach ($files as $file => $time){
if($count > 10){
unlink($file);
}
$count++;
}
You could simply sort the result of scandir by the returned files' modification dates:
/**
* #return string[]
*/
function getOldestFiles(string $folderPath, int $count): array
{
// Grab all the filenames
$filenames = #scandir($folderPath);
if ($filenames === false) {
throw new InvalidArgumentException("{$folderPath} is not a valid folder.");
}
// Ignore folders (remove from array)
$filenames = array_filter($filenames, static function (string $filename) use ($folderPath) {
return is_file($folderPath . DIRECTORY_SEPARATOR . $filename);
});
// Sort by ascending last modification date (older first)
usort($filenames, static function (string $file1Name, string $file2Name) use ($folderPath) {
return filemtime($folderPath . DIRECTORY_SEPARATOR . $file1Name) <=> filemtime($folderPath . DIRECTORY_SEPARATOR . $file2Name);
});
// Return the first $count
return array_slice($filenames, 0, $count);
}
Usage:
$folder = '/some/folder';
$oldestFiles = getOldestFiles($folder, 10);
foreach ($oldestFiles as $file) {
unlink($folder . '/' . $file);
}
Note: this is obviously over-commented for the purpose of this answer.
I have a CSV list which contains URL/Link of some image.
So I had tried this below code;
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
col1 = $col[0];
for ($i = 0; $i < count($col1); $i++){
if ( !$col1[$i] == null){
echo $col1[$i]. ",<br>";
file_put_contents("images/img.jpg", $elements[$i] . "\n", FILE_APPEND);
}
}
}
fclose($handle);
}
the code is working, but it's replacing the image at the end of execution I'm getting only one pic which's Last row of csv & Getting error Max_execution time.
Try this out.
$handle = fopen($csv_file, "r");
$destination = 'images/';
if ($handle) {
while ($columns = fgetcsv($handle)) {
foreach ($columns as $imageUrl) {
if (!empty($imageUrl)) {
file_put_contents(
$destination . basename($imageUrl),
file_get_contents($imageUrl)
);
}
}
}
}
What it does is open the CVS, loops through it, row at a time, checks that the image URL isn't empty, downloads it and puts it into your directory. You of course need to make sure that PHP has the rights to write to that directory. The code also doesn't handle conflicts in the naming of images, so a further improvement would be to add some clash detection and append a counter before the suffix.
I'm trying to make scandir(); function go beyond its written limits, I need more than the alpha sorting it currently supports. I need to sort the scandir(); results to be sorted by modification date.
I've tried a few solutions I found here and some other solutions from different websites, but none worked for me, so I think it's reasonable for me to post here.
What I've tried so far is this:
function scan_dir($dir)
{
$files_array = scandir($dir);
$img_array = array();
$img_dsort = array();
$final_array = array();
foreach($files_array as $file)
{
if(($file != ".") && ($file != "..") && ($file != ".svn") && ($file != ".htaccess"))
{
$img_array[] = $file;
$img_dsort[] = filemtime($dir . '/' . $file);
}
}
$merge_arrays = array_combine($img_dsort, $img_array);
krsort($merge_arrays);
foreach($merge_arrays as $key => $value)
{
$final_array[] = $value;
}
return (is_array($final_array)) ? $final_array : false;
}
But, this doesn't seem to work for me, it returns 3 results only, but it should return 16 results, because there are 16 images in the folder.
function scan_dir($dir) {
$ignored = array('.', '..', '.svn', '.htaccess');
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file, $ignored)) continue;
$files[$file] = filemtime($dir . '/' . $file);
}
arsort($files);
$files = array_keys($files);
return ($files) ? $files : false;
}
This is a great question and Ryon Sherman’s answer provides a solid answer, but I needed a bit more flexibility for my needs so I created this newer function: better_scandir.
The goal is to allow having scandir sorting order flags work as expected; not just the reverse array sort method in Ryon’s answer. And also explicitly setting SORT_NUMERIC for the array sort since those time values are clearly numbers.
Usage is like this; just switch out SCANDIR_SORT_DESCENDING to SCANDIR_SORT_ASCENDING or even leave it empty for default:
better_scandir(<filepath goes here>, SCANDIR_SORT_DESCENDING);
And here is the function itself:
function better_scandir($dir, $sorting_order = SCANDIR_SORT_ASCENDING) {
/****************************************************************************/
// Roll through the scandir values.
$files = array();
foreach (scandir($dir, $sorting_order) as $file) {
if ($file[0] === '.') {
continue;
}
$files[$file] = filemtime($dir . '/' . $file);
} // foreach
/****************************************************************************/
// Sort the files array.
if ($sorting_order == SCANDIR_SORT_ASCENDING) {
asort($files, SORT_NUMERIC);
}
else {
arsort($files, SORT_NUMERIC);
}
/****************************************************************************/
// Set the final return value.
$ret = array_keys($files);
/****************************************************************************/
// Return the final value.
return ($ret) ? $ret : false;
} // better_scandir
Alternative example..
$dir = "/home/novayear/public_html/backups";
chdir($dir);
array_multisort(array_map('filemtime', ($files = glob("*.{sql,php,7z}", GLOB_BRACE))), SORT_DESC, $files);
foreach($files as $filename)
{
echo "<a>".substr($filename, 0, -4)."</a><br>";
}
Another scandir keep latest 5 files:
public function checkmaxfiles()
{
$dir = APPLICATION_PATH . '\\modules\\yourmodulename\\public\\backup\\';
// '../notes/';
$ignored = array('.', '..', '.svn', '.htaccess');
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file, $ignored)) continue;
$files[$file] = filemtime($dir . '/' . $file);
}
arsort($files);
$files = array_keys($files);
$length = count($files);
if($length < 4 ){
return;
}
for ($i = $length; $i > 4; $i--) {
echo "Erase : " .$dir.$files[$i];
unlink($dir.$files[$i]);
}
}
I'd like to randomly load images from a directory and have a button somewhere that refreshes the entire page. Here's the current code I have now:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
The problem is it loads all 400,000 images at once. I only want 30 to load. 30 random images from the directory. I tried looking up some code such as modifying the above to this:
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
if (++$i == 2) break;
}
?>
But it seems to do absolutely nothing.. So if someone can help me get 30 random photos from that directory to load and have some type of reload button, that would be of great help.
Thank you in advance
Here is my solution with a cache:
<?php
define('CACHE_FILE', 'mycache.tmp');
define('CACHE_TIME', 20); // 20 seconds (for testing!)
define('IMG_COUNT', 30);
define('IMG_DIR', '../public/wp-content/uploads/2012/01');
/**
* Loads the list (an array) from the cache
* Returns FALSE if the file couldn't be opened or the cache was expired, otherwise the list (as an array) will be returned.
*/
function LoadListFromCache($cacheFile, $cacheTime)
{
if ( file_exists($cacheFile) )
{
$fileHandle = fopen($cacheFile, 'r');
if ( !$fileHandle )
return false;
// Read timestamp (separated by "\n" from the content)
$timestamp = intval( fgets($fileHandle) );
fclose($fileHandle);
// Expired?
if ( $timestamp+$cacheTime > time() )
return false;
else
{
// Unserialize the content!
$content = file_get_contents($cacheFile);
$content = substr( $content, strpos($content, "\n") );
$list = unserialize($content);
return $list;
}
}
return false;
}
/**
* Caches the passed array
* Returns FALSE if the file couldn't be opened, otherwise TRUE.
*/
function SaveListToCache($cacheFile, $list)
{
$fileHandle = fopen($cacheFile, 'w');
if ( $fileHandle === FALSE ) return false;
fwrite($fileHandle, time());
fwrite($fileHandle, "\n");
fwrite($fileHandle, serialize($list));
fclose($fileHandle);
return true;
}
/**
* Generates the list of all image files (png, jpg, jpeg) and caches it.
* Returns the list as an array.
*/
function GenerateList()
{
$a = array();
$dir = IMG_DIR;
if ($handle = opendir($dir))
{
while (false !== ($file = readdir($handle)))
{
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
SaveListToCache(CACHE_FILE, $a);
return $a;
}
function GetRandomImages($list, $count)
{
$listCount = count($list);
$randomEntries = array();
for ($i=0; $i<$count; $i++)
{
$randomEntries[] = $list[ rand(0, $listCount) ];
}
return $randomEntries;
}
// This code will execute the other functions!
$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);
if ( $list === FALSE )
{
$list = GenerateList();
}
$images = GetRandomImages($list, IMG_COUNT);
foreach ($images as $image)
{
echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';
}
If you have 400,000 images then I think reading the entire directory everytime is going to be an expensive means of showing random images. I would use a database instead and store the file paths in it.
If you want to use your existing code then think of it this way. You have an array of length n containing image names. You want to generate thirty random numbers between 0 and n-1. Then display the image associated with that position in the array. I'm not a php expert, but here is some pseudocode:
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
for ( i=0; i < 30; i++) {
//generate a random number between 0 and N-1
random = rand(0, $a.length - 1);
//display that image in the array
echo "<img src='" . $dir . '/' . $a[random] . "' />";
}
You need to create a new variable for the counter instead of using $i
For example, you can do this instead
$j = 0;
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
$j++;
if ($j >= 30)
{
break;
}
}
EDIT: Perhaps for the random part you can first generate a random number between 0 and n-1 where n is the total number of the images and then just echo out the image from the array with the index number.
Instead of using foreach, I think you'll need a for loop instead.
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 30; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
You should maybe only read 30 file from your directory. Stop looking in the directory when readdir return false or your array's length is 30.
This should work
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle)) && (count($a) <= 30) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
It may not execute (I didn't try). But the idea is here
For randomize the image: shuffle($a) should do the trick
in simplest way ,
you can use
find , sort , head
commands in linux,in conjuction with PHP's built in
exec()
function to get 30 random image links easily , the folowing snippet lists how to do it
(How to get random 30 image links in an array.)
<?php
$picdir = "directory/containing/pictures"; // directory containing only pictures
exec("find " . $picdir . " | sort -R | head -30 ",$links);
while(list($index,$val) = each($links) ) {
echo "<img src =" .$val . "> <br/>"; // shows image
}
?>
Here $links array contain random 30 image names(from folder) with complete path . This is used with img tag in echo to generate images
Here $picdir has the path of the directory having images and it is assumed that dirrectory is having only image files . in other case its only matter of modifying find command to exclude non image files(such as using grep command to exclude )
How to count the number of files in a directory using PHP?
Please answer for the following things:
1. Recursive Search: The directory (which is being searched) might be having several other directories and files.
2. Non-Recursive Search: All the directories should be ignored which are inside the directory that is being searched. Only files to be considered.
I am having the following code, but looking for a better solution.
<?php
$files = array();
$dir = opendir('./items/2/l');
while(($file = readdir($dir)) !== false)
{
if($file !== '.' && $file !== '..' && !is_dir($file))
{
$files[] = $file;
}
}
closedir($dir);
//sort($files);
$nooffiles = count($files);
?>
Recursive:
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
$count = 0;
while($it->next()) $count++;
Most of the mentioned ways for "Non-Recursive Search" work, though it can be shortened using PHP's glob filesystem function.
It basically finds pathnames matching a pattern and thus can be used as:
$count = 0;
foreach (glob('path\to\dir\*.*') as $file) {
$count++;
}
The asterisk before the dot denotes the filename, and the one after denotes the file extension. Thus, its use can further be extended to counting files with specific filenames, specific extensions or both.
non-recrusive:
$dir = opendir('dir/');
$i = 0;
while (false !== ($file = readdir($dir))){
if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
}
echo "There were $i files";
recrusive:
function crawl($dir){
$dir = opendir($dir);
$i = 0;
while (false !== ($file = readdir($dir)){
if (is_dir($file) and !in_array($file, array('.', '..'))){
$i += crawl($file);
}else{
$i++;
}
}
return $i;
}
$i = crawl('dir/');
echo "There were $i files";
Might be useful for you:
http://www.php.net/manual/en/class.dir.php
http://www.php.net/manual/en/function.is-file.php
But, i think, there is no other good solutions.
Rather than posting code for you, I would provide the outline of what you should do as you seem to have the basic code already.
Place your code in a function. Have two parameters ($path, $recursive = FALSE) and within your code, separate the is_dir() and if that's true and the recursive flag is true, then pass the new path (path to the current file) back to the function (self reference).
Hope this helps you learn, rather than copy paste :-)
Something like this might work:
(might need to add some checks for '/' for the $dir.$file concatenation)
$files = array();
$dir = './items/2/l';
countFiles($dir, $files); // Recursive
countFiles($dir, $files, false); // Not recursive;
var_dump(count($files));
function countFiles($directory, &$fileArray, $recursive = true){
$currDir = opendir($directory);
while(($file = readdir($dir)) !== false)
{
if(is_dir($file) && $recursive){
countFiles($directory.$fileArray, $saveArray);
}
else if($file !== '.' && $file !== '..' && !is_dir($file))
{
$fileArray[] = $file;
}
}
}
Recursive:
function count_files($path) {
// (Ensure that the path contains an ending slash)
$file_count = 0;
$dir_handle = opendir($path);
if (!$dir_handle) return -1;
while ($file = readdir($dir_handle)) {
if ($file == '.' || $file == '..') continue;
if (is_dir($path . $file)){
$file_count += count_files($path . $file . DIRECTORY_SEPARATOR);
}
else {
$file_count++; // increase file count
}
}
closedir($dir_handle);
return $file_count;
}
Non-Recursive:
$directory = ".. path/";
if (glob($directory . "*.") != false)
{
$filecount = count(glob($directory . "*."));
echo $filecount;
}
else
{
echo 0;
}
Courtesy of Russell Dias
You can use the SPL DirectoryIterator to do this in a non-recursive (or with a recursive iterator in a recursive) fashion:
iterator_count(new DirectoryIterator($directory));
It's good to note that this will not just count regular files, but also directories, dot files and symbolic links. For regular files only, you can use:
$directory = new DirectoryIterator($directory);
$count = 0;
foreach($directory as $file ){ $count += ($file->isFile()) ? 1 : 0;}
PHP 5.4.0 also offers:
iterator_count(new CallbackFilterIterator($directory, function($current) { return $current->isFile(); }));
$dir = opendir('dir/');
$i = 0;
while (false !== ($file = readdir($dir))){
if (!in_array($file, array('.', '..' ))and (!is_dir($file)))
$i++;
}
echo "There were $i files";