XAMPP rename function - php

I'm trying to write a bulk rename in this way:
if ($handle = opendir('../../upload_files')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(", ","_",$fileName);
rename($fileName, $newName);
$count++;
}
closedir($handle);
echo $count." files renamed";
}
But when I run the script, I get a warning:
Warning: rename(..,..) [function.rename]: No error in E:\WEBS\rename.php on line 6
What is causing the error?

If the target file already exists, PHP is known for such error under Windows environment.
There's a known bug for PHP 5.3 https://bugs.php.net/bug.php?id=48771 with similar error message.
I recommend trying out following modification of your code (it's based on your code, just with some corrections)
$dir = "../../upload_files";
if ($handle = opendir($dir))
{
while (false !== ($fileName = readdir($handle)))
{
if (!isset($count)) $count = 0;
if ($fileName == ".." || $fileName == ".") continue;
$newName = str_replace(", ","_",$fileName);
copy($dir.$fileName, $dir.$newName);
$count++;
}
closedir($handle);
echo $count." files renamed";
}

Related

Bulk update in php using some conditions for filename

I have a folder and have multiple files over there. The file has the below pattern for example.
The file names should be renamed from
file1.mp4.png
file2.flv.png
file3.xxx.png (xxx - can be anything)
to as follows (the last extension remains).
file1.png
file2.png
file3.png
Files having non-png extension should be left untouched.
I am using the logic mentioned in Bulk Rename Files in a Folder - PHP
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$newName = (how to get new filename) // I am struck here
rename($fileName, $newName);
}
closedir($handle);
}
How best I can do this to do a bulk update?
<?php
// Select all PNG Files
$matches = glob("*.[pP][nN][gG]");
// check if we found any results
if ( is_array ( $matches ) ) {
// loop through all files
foreach ( $matches as $filename) {
// rename your files here
$newfilename = current(explode(".", $filename)).".png";
rename($filename, $newfilename);
echo "$filename -> $newfilename";
}
}
?>
try this
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$arr_names = explode(".", $fileName);
$size = sizeof($arr_names);
$ext = $arr_names[$size-1];
if($fileName=="." || $fileName==".." || is_dir($fileName))
{
continue; // skip png
}
if($ext=='png' || $ext=='PNG')
{
$newName = $arr_names[0].".".$ext;
rename($fileName, $newName);
}
}
closedir($handle);
}
Shortest using regex
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace("/\.(.*?)\.png$/", '', $fileName); // removes .xxx.png
rename($fileName, ($newName . '.png')); // renames file1.png
}
closedir($handle);
}

PHP auto-incude from a folder

I want to create a system which will include any .php file from a folder, similar to wordpress\plugins folder. Preferably drag and drop.
Any ideas how to do it?
Question is not clear...
read the folder files
scroll through the files found
if PHP - include it
<?php
function scandir2($dir)
{
$out = array();
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
while (($file = readdir($dh)) !== false)
{
if ($file == '.' or $file == '..') continue;
if (!is_dir($dir . '/'. $file))
{
$out[] = $dir . '/' . $file;
}
}
closedir($dh);
}
}
sort($out);
return $out;
}
$i=scandir2(".");
foreach($i as $name)
{
if(strstr($name ,'.php'))
include($name);
}
?>
this code scan directory and include php files ...
Here is the code to do that:
foreach (glob("/path/*.php") as $filename) {
include $file;
}
The glob() function returns an array of all .php files on the specified path.
Here is how I would do it...
<?php
$dirPath = '/path/to/files';
if ($handle = opendir($dirPath)) {
/* loop over files in directory */
while (false !== ($entry = readdir($handle))) {
/* find extension */
$ext = substr($entry,-3);
$ext = strtolower($ext);
/* include file if extension is PHP */
if ($ext === 'php') {
include_once($dirPath .'/'. $entry);
} //if
} //if
closedir($handle);
} //if
Note that there is several security concerns and possibly performance concerns.

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);

zipping a folder's content php, not a whole folder

I'm looking for a solution to zip a folder's content, including all subfolders that are in the folder, but not the main folder itself.
I started from this function, that adds a whole folder to a zip archive
function addFolderToZip($dir, $zipArchive){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
$zipArchive->addEmptyDir($dir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories
if( ($file !== ".") && ($file !== "..")){
addFolderToZip($dir . $file . "/", $zipArchive);
}
}else{
// Add the files
$zipArchive->addFile($dir . $file);
}
}
}
}
}
but I don't see how to change the function to (maybe using a third argument ?)
$z = new ZipArchive();
$z->open("zips/new.zip", ZIPARCHIVE::CREATE);
addFolderToZip("unzipped/",$z);
$z->close();
I've got it, I have created an argument $localpath, set to "":
function add_folder_in_path($folder_path,$local_path,$z)
{
$dh=opendir($folder_path);
while (($file = readdir($dh)) !== false)
{
if( ($file !== ".") && ($file !== ".."))
{
if (is_file($folder_path.$file))
{
$z->addFile($folder_path.$file,$local_path.$file);
}
else
{
add_folder_in_path($folder_path.$file."/",$local_path.$file."/",$z);
}
}
}
}
Here is how I call it
$z = new ZipArchive();
$z->open("zipped/new.zip", ZIPARCHIVE::CREATE);
echo "<br>";
add_folder_in_path("myzips/","",$z);
$z->close();

php readdir and is_dir

I am testing out the functions of directory handling. I have a fold/directory that contains the following:
0 File folder
false File folder
my_pictures File folder
MVI_3094 mov file
img01 jpeg image
etc...
I wrote the following code to traverse the directory and print out specific resutls
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($entry))
{
echo "Directory:$entry<br />";
}
}
My only problem is that the second "if" statement does not output the results of
echo "Directory:$entry<br />";
even though the entry is a directory. I have checked the entry manually with the "var_dump" function and it returns true as a directory.
Any suggestions would help
Try this and check. Just a try...
$handle = opendir("files/");
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
elseif(is_dir("files/".$entry))
{
echo "Directory:$entry<br />";
}
}
$entry is relative... is_dir expects an absolute path.
Try:
if(is_dir("files/".$entry))
readdir() is just returning the filenames. Your code is therefore looking for the files in the current directory rather than the subdirectory.
This will just probe the basename of whatever directory entry:
is_dir($entry)
The opendir() result list will be relative to the directory you gave for reading. So you need to use:
is_dir("files/$entry")
Your problem is that in elseif(is_dir($entry)) {, entry is equal to some string like "file.txt" or "somedirectory", which isn't a path pointing to a file at all. It needs to be "files/file.txt".
Try this:
$dir = "files/";
$handle = opendir($dir);
while(($entry = readdir($handle)) !== false)
{
if($entry == "." || $entry == "..")
{
continue;
}
if(is_dir($dir.$entry))
{
echo "Directory:$entry<br />";
}
}
Try using the DirectoryIterator:
$iterator = new \DirectoryIterator(realpath('files/'));
foreach($iterator as $file){
if($file->isDot())
continue;
if($file->isDir())
printf('Directory: %s <br/>', $file->getRealPath());
}

Categories