I have created folder based on year and month (while I upload image), eg: if I upload an pdf on February 1 2018 then I have created folder 2018 and folder 2.
$filename = $_SERVER['DOCUMENT_ROOT'] . '/' . 'folder1/admin/slip' . '/' . $year . '';
$filename2 = $filename . '/' . $month;
if (file_exists($filename)) {
if (file_exists($filename2) == false) {
mkdir($filename2, 0777);
}
} else {
mkdir($filename, 0777);
}
If I again upload an pdf in February, I want to delete this folder and create it again. I use the following code
rmdir($filename2)
but its not working.
please help me
Use this function for delete file.
unlink( $filepath)
<?php
delete_files('/path/for/the/directory/');
/*
* php delete function that deals with directories recursively
*/
function delete_files($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file ){
delete_files( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
}
?>
Related
I want the script to go into the folder 'images', take every file, cut the first four characters and rename it.
PHP
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>
This is how the files in the images folder are named:
0,78test-1.jpg
0,32test-2.jpg
0,43test-3.jpg
0,99test-4.jpg
and this is what i want them to look like:
test-1.jpg
test-2.jpg
test-3.jpg
test-4.jpg
The problem is the script cuts out the first 8, 12 or 16 characters, not four as i want it! So when i execute it my files look like this:
-1.jpg
-2.jpg
-3.jpg
-4.jpg
UPDATE
I also tracked the packages to make sure i am not executing the script multiple times. The script is only executed once!
A slightly different approach though essentially the same with the substr part this worked fine for tests on local system.
$dir='c:/temp2/tmpimgs/';
$files=glob( $dir . '*.*' );
$files=preg_grep( '#(\.jpg$|\.jpeg$|\.png$)#i', $files );
foreach( $files as $filename ){
try{
$path=pathinfo( $filename, PATHINFO_DIRNAME );
$name=pathinfo( $filename, PATHINFO_BASENAME );
$newname=$path . DIRECTORY_SEPARATOR . substr( $name, 4, strlen( $name ) );
if( strlen( $filename ) > 4 ) rename( $filename, $newname );
} catch( Exception $e ){
echo $e->getTraceAsString();
}
}
You may want to try this little Function. It would do just the proper renaming for you:
<?php
$path = './images/';
function renameFilesInDir($dir){
$files = scandir($dir);
// LOOP THROUGH THE FILES AND RENAME THEM
// APPROPRIATELY...
foreach($files as $key=>$file){
$fileName = $dir . DIRECTORY_SEPARATOR . $file;
if(is_file($fileName) && !preg_match("#^\.#", $file)){
$newFileName = preg_replace("#\d{1,},\d{1,}#", "", $fileName);
rename($fileName, $newFileName);
}
}
}
renameFilesInDir($path);
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
//change below line and find first occurence of '-' and then replace everything before this with 'test' or any keyword
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>
Basically, my requirement is, I want to move all files from one folder to another folder using PHP scripts. Any one can help me. I am trying this, but I am getting error
$mydir = dirname( __FILE__ )."/html/images/";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.");
foreach($files as $file){
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}
// images folder creation using php
$mydir = dirname( __FILE__ )."/html/images";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.*");
foreach($files as $file){
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}
Try this :
<?php
$src = 'pictures';
$dst = 'dest';
$files = glob("pictures/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
}
?>
foreach(glob('old_directory/*.*') as $file) {
copy('old_directory/'.$file, 'new_directory/'.$file);
}
Use array_map:
// images folder creation using php
function copyFile($file) {
$file_to_go = str_replace("images/","html/images/",$file);
copy($file, $file_to_go);
}
$mydir = dirname( __FILE__ )."/html/images";
if(!is_dir($mydir)){
mkdir("html/images");
}
// Move all images files
$files = glob("images/*.*");
print_r(array_map("copyFile",$files));
This One Works for me...........
Thanks to this man
http://www.codingforums.com/php/146554-copy-one-folder-into-another-folder-using-php.html
<?php
copydir("admin","filescreate");
echo "done";
function copydir($source,$destination)
{
if(!is_dir($destination)){
$oldumask = umask(0);
mkdir($destination, 01777); // so you get the sticky bit set
umask($oldumask);
}
$dir_handle = #opendir($source) or die("Unable to open");
while ($file = readdir($dir_handle))
{
if($file!="." && $file!=".." && !is_dir("$source/$file"))
copy("$source/$file","$destination/$file");
}
closedir($dir_handle);
}
?>
This should work just fine:
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file))
{
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file)
{
unlink($file);
}
or with rename() and some error checking:
$srcDir = 'dir1';
$destDir = 'dir2';
if (file_exists($destDir)){
if (is_dir($destDir)) {
if (is_writable($destDir)) {
if ($handle = opendir($srcDir)) {
while (false !== ($file = readdir($handle))) {
if (is_file($srcDir . '/' . $file)) {
rename($srcDir . '/' . $file, $destDir . '/' . $file);
}
}
closedir($handle);
} else {
echo "$srcDir could not be opened.\n";
}
} else {
echo "$destDir is not writable!\n";
}
} else {
echo "$destDir is not a directory!\n";
}
} else {
echo "$destDir does not exist\n";
}
You can use this recursice function.
<?php
function copy_directory($source,$destination) {
$directory = opendir($source);
#mkdir($destination);
while(false !== ( $file = readdir($directory)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($source . '/' . $file) ) {
copy_directory($source . '/' . $file,$destination . '/' . $file);
}
else {
copy($source . '/' . $file,$destination . '/' . $file);
}
}
}
closedir($directory);
}
?>
Referrence : http://php.net/manual/en/function.copy.php
I had a similar situation where I needed to copy from one domain to another, I solved it using a tiny adjustment to the "very easy answer" given by "coDe murDerer" above:
Here is exactly what worked in my case, you can as well adjust to suit yours:
foreach(glob('../folder/*.php') as $file) {
$adjust = substr($file,3);
copy($file, '/home/user/abcde.com/'.$adjust);
Notice the use of "substr()", without it, the destination becomes '/home/user/abcde.com/../folder/', which might be something you don't want.
So, I used substr() to eliminate the first 3 characters(../) in order to get the desired destination which is '/home/user/abcde.com/folder/'. So, you can adjust the substr() function and also the glob() function until it fits your personal needs. Hope this helps.
The purpose of this question can be served by writing independent function for each source & destination directory in an include file but I'm looking for a better approach.
The following function copy files from one source directory to one destination directory.
How can I use this function to copy file from another source directory to destination directory?
Is array(); applicable here or explode(); shall be the right choice or none of these is applicable in this case?
if (isset($_POST['submit'])) {
$old_umask = umask(0);
if (!is_dir($dst)) mkdir($dst, 0777);
umask($old_umask);
function recurse_copy($src,$dst) {
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
//echo "$src";
}
$dir = $_POST['name'];
$src = "/home/user/public_html/directory/subdirectory/source/";
$dst = "/home/user/public_html/directory/subdirectory/destination/$dir/";
recurse_copy($src,$dst);
}
In my PHP project all of the class files are contained in a folder called 'classes'. There is one file per class and as more and more functionality is added to the application the classes folder is growing larger and less organized. Right now this code, in an initialization file, autoloads classes for the pages in the app:
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
If subfolders were to be added to the existing 'classes' folder and the class files organized within these subfolders, is there a way to modify the the autoload code so it still works?
For example - assume the subfolders within the classes folder looks like this:
DB
login
cart
catalog
I recoomend that you look at PSR standards at : http://www.php-fig.org
Also this tutorial will help you build and understand one for yourself.
http://www.sitepoint.com/autoloading-and-the-psr-0-standard/
Snippet that takes all subfolder :
function __autoload($className) {
$extensions = array(".php", ".class.php", ".inc");
$paths = explode(PATH_SEPARATOR, get_include_path());
$className = str_replace("_" , DIRECTORY_SEPARATOR, $className);
foreach ($paths as $path) {
$filename = $path . DIRECTORY_SEPARATOR . $className;
foreach ($extensions as $ext) {
if (is_readable($filename . $ext)) {
require_once $filename . $ext;
break;
}
}
}
}
My solution
function load($class, $paste){
$dir = DOCROOT . "\\" . $paste;
foreach ( scandir( $dir ) as $file ) {
if ( substr( $file, 0, 2 ) !== '._' && preg_match( "/.php$/i" , $file ) ){
require $dir . "\\" . $file;
}else{
if($file != '.' && $file != '..'){
load($class, $paste . "\\" . $file);
}
}
}
}
function autoloadsystem($class){
load($class, 'core');
load($class, 'libs');
}
spl_autoload_register("autoloadsystem");
Root
|-..
|-src //class Directory
|--src/database
|--src/Database.php // Database Class
|--src/login
|--src/Login.php // Login Class
|-app //Application Directory
|--app/index.php
|-index.php
-----------------------------------
Code Of index.php in app folder to Autoload All the Classes from The src folder.
spl_autoload_register(function($class){
$BaseDIR='../src';
$listDir=scandir(realpath($BaseDIR));
if (isset($listDir) && !empty($listDir))
{
foreach ($listDir as $listDirkey => $subDir)
{
$file = $BaseDIR.DIRECTORY_SEPARATOR.$subDir.DIRECTORY_SEPARATOR.$class.'.php';
if (file_exists($file))
{
require $file;
}
}
}});
Code Of index.php in root folder to Autoload All the Classes from The src folder.
change the variable $BaseDIR,
$BaseDIR='src';
autoload.php
<?php
function __autoload ($className) {
$extensions = array(".php");
$folders = array('', 'model');
foreach ($folders as $folder) {
foreach ($extensions as $extension) {
if($folder == ''){
$path = $folder . $className . $extension;
}else{
$path = $folder . DIRECTORY_SEPARATOR . $className . $extension;
}
if (is_readable($path)) {
include_once($path);
}
}
}
}
?>
index.php
include('autoload.php');
Here is the one I'm using
spl_autoload_register(function ($class_name) {
//Get all sub directories
$directories = glob( __DIR__ . '/api/v4/core/*' , GLOB_ONLYDIR);
//Find the class in each directory and then stop
foreach ($directories as $directory) {
$filename = $directory . '/' . $class_name . '.php';
if (is_readable($filename)) {
require_once $filename;
break;
}
}
});
Load files from "inc" subfolder using "glob"
/**
* File autoloader
*/
function load_file( $file_name ) {
/**
* The folder to where we start looking for files
*/
$base_folder = __DIR__ . DIRECTORY_SEPARATOR ."inc". DIRECTORY_SEPARATOR . "*";
/**
* Get all sub directories from the base folder
*/
$directories = glob( $base_folder, GLOB_ONLYDIR );
/**
* look for the specific file
*/
foreach ( $directories as $key => $directory ) {
$file = $directory . DIRECTORY_SEPARATOR . $file_name . ".php";
/**
* Replace _ by \ or / may differ from OS
*/
$file = str_replace( '_', DIRECTORY_SEPARATOR, $file );
/**
* Check for file if its readable
*/
if ( is_readable( $file ) ) {
require_once $file;
break;
}
}
}
/**
* Autoload file using PHP spl_autoload_register
* #param $callbak function
*/
spl_autoload_register( 'load_file' );
by mistaken I upload my code on server with svn files and folders. I don't have access for SSH so can't run commands.
so is there any php code by using which I can delete all .svn folders from my projects.
EDIT:
Finding all the .svn folders is a complicated process to do that you need a to use recursive functions.
Link to code: http://pastebin.com/i5QMGm1C
Or view it here:
function rrmdir($dir)
{
foreach(glob($dir . '/*') as $path) {
if(is_dir($path)){
rrmdir($path);
}
else{
unlink($path);
}
}
foreach(glob($dir . '/.*') as $path) {
if(is_dir($path)){
$base_name = basename($path);
if ($base_name != '..' && $base_name != '.'){
rrmdir($path);
}
}
else{
unlink($path);
}
}
rmdir($dir);
}
function delete_dir($base, $dir)
{
static $count = 0;
foreach (glob($base . '/*') as $path){
if(is_dir($path)){
delete_dir($path, $dir);
}
}
foreach (glob($base . '/.*') as $path){
if(is_dir($path)){
$base_name = basename($path);
if ($base_name != '..' && $base_name != '.'){
if ($base_name == $dir){
rrmdir($path);
echo 'Directory (' . $path . ') Removed!<br />';
$count++;
}
else {
delete_dir($path, $dir);
}
}
}
}
return $count;
}
$base = $_SERVER['DOCUMENT_ROOT'];
$dir = '.svn';
$count = delete_dir($base, $dir);
echo 'Total: ' . $count . ' Folders Removed!';
I get a solution here it is
copied from lateralcode with little modification
$path = $_SERVER['DOCUMENT_ROOT'].'/work/remove-svn-php/'; // path of your directory
header( 'Content-type: text/plain' ); // plain text for easy display
// preconditon: $dir ends with a forward slash (/) and is a valid directory
// postcondition: $dir and all it's sub-directories are recursively
// searched through for .svn directories. If a .svn directory is found,
// it is deleted to remove any security holes.
function removeSVN( $dir ) {
//echo "Searching: $dir\n\t";
$flag = false; // haven't found .svn directory
$svn = $dir . '.svn';
if( is_dir( $svn ) ) {
if( !chmod( $svn, 0777 ) )
echo "File permissions could not be changed (this may or may not be a problem--check the statement below).\n\t"; // if the permissions were already 777, this is not a problem
delTree( $svn ); // remove the .svn directory with a helper function
if( is_dir( $svn ) ) // deleting failed
echo "Failed to delete $svn due to file permissions.";
else
echo "Successfully deleted $svn from the file system.";
$flag = true; // found directory
}
if( !$flag ) // no .svn directory
echo 'No .svn directory found.';
echo "\n\n";
$handle = opendir( $dir );
while( false !== ( $file = readdir( $handle ) ) ) {
if( $file == '.' || $file == '..' ) // don't get lost by recursively going through the current or top directory
continue;
if( is_dir( $dir . $file ) )
removeSVN( $dir . $file . '/' ); // apply the SVN removal for sub directories
}
}
// precondition: $dir is a valid directory
// postcondition: $dir and all it's contents are removed
// simple function found at http://www.php.net/manual/en/function.rmdir.php#93836
function delTree( $dir ) {
$files = glob( $dir . '*', GLOB_MARK ); // find all files in the directory
foreach( $files as $file ) {
if( substr( $file, -1 ) == '/')
delTree( $file ); // recursively apply this to sub directories
else
unlink( $file );
}
if ( is_dir( $dir ) ){
//echo $dir;
// die;
rmdir( $dir ); // remove the directory itself (rmdir only removes a directory once it is empty)
}
}
// remove all .svn directories in the
// current directory and sub directories
// (recursively applied)
removeSVN($path);