copy images from one folder to sub folder in php - php

I am facing a problem. I have some images stored in D://Images. I have to copy these images into D://Images/Modified. I tried but I did not get any output.
This is my code:
define("BASE_IMAGE_PATH","D:\\");
define("IMAGE_FOLDER_NAME","2014finalfour\\");
define("IMAGE_FOLDER_NAME_MODIFIED","modified");
define("IMAGE_File_Path",BASE_IMAGE_PATH.IMAGE_FOLDER_NAME);
define("IMAGE_File_Path_Modified", BASE_IMAGE_PATH.IMAGE_FOLDER_NAME.IMAGE_FOLDER_NAME_MODIFIED);
$srcdir=constant("IMAGE_File_Path");
$destdir=constant("IMAGE_File_Path_Modified");
echo $destdir;
if (!file_exists(IMAGE_File_Path_Modified))
{
mkdir(IMAGE_File_Path_Modified, 0777, true);
}
$srcdir=opendir($srcdir);
while($readFile = readdir($srcdir))
{
if($readFile != '.' && $readFile != '..')
{
if (!file_exists($readFile))
{
if(copy($srcdir . $readFile, $destdir . $readFile))
{
echo "Copy file";
}
else
{
echo "Canot Copy file";
}
}
}
}
closedir($srcdir);
Please help me to sought out it. It says it can not copy the file. copy() expects parameter 1 to be a valid path, resource given in C:\wamp\www\marcs\testmysql.php on line 3

You could use the copy() function :
copy('foo/test.php', 'bar/test.php');
example:
<?php
$file = 'images/folder/one.jpg';
$newfile = 'Images/folder/one_thumb.jpg';
if (!copy($file, $newfile)) {
echo "failed to copy";
}
Makes a copy of the file source to dest.
If the destination file already exists, it will be overwritten.

Related

Changing php content after copy files

I have the code bellow where I'm creating a new folder and copying some files from another folder, and it's working fine.
Now I need to go on each php file inside new folder and change the word "empty" by some word passed through $_POST["variable"].
Maybe by str_replace but I'm stuck in the logic.
Thanks in advance!
if (!file_exists("/home//public_html/new_conf_folder/"))
{
mkdir("/home//public_html/new_conf_folder/", 0755, true);
$source = "/home/public_html/conf_folder/";
$destination = "/home/public_html/new_conf_folder";
$directory = opendir($source);
while(($file = readdir($directory)) != false)
{
copy($source.'/' .$file, $destination.'/'.$file);
}
}
Try this code its working for me:
// file_process.php
$destination="./"; // Current Directory
if (file_exists($destination))
{
$directory = opendir($destination);
while(($file = readdir($directory)) != false)
{
//echo $file."<br/>";
$contents=file_get_contents($file);
$contents=str_replace("\"empty\"",$_POST['variable'],$contents);
//$contents=str_replace("\"empty\"",$_POST['variable'],$contents); // use this if the word with qouts
//echo $contents;
$bytes_written=file_put_contents($file,$contents);
if($bytes_written>0)echo "File [$file] has been successfully processed.";
else echo "Process Failed.";
}
}

How to check a folder contains .csv files?

I need to check whether a folder contains csv files or not. Using PHP
I need to show an error message if someone try to upload any csv into a specific folder if there is already existing a csv.
Use glob() to find all files matching a wildcard. It returns an array of the matches, so you can check if the array is empty.
$files = glob("$dirname/*.csv");
if (!empty($files)) {
die("Error: The directory already has a .csv file");
}
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "Die Datei $filename existiert";
} else {
echo "Die Datei $filename existiert nicht";
}
?>
From: http://php.net/manual/de/function.file-exists.php
Loop over the files of directory to check whether it contains csv or not.
$files=scandir("/path/to/dir");
foreach($files as $fileName)
{
if(preg_match("/\.csv$/", $fileName))
{
throw new Exception("/path/to/dir contains csv file with filename: $fileName");
}
}
$dir = 'folder';
echo (count(glob("$dir/*.csv")) === 0) ? 'Empty' : 'Not empty';
You can use glob() function. http://php.net/manual/tr/function.glob.php
Also #Barmar answer is look like doing job well.
<?php
$directory = new DirectoryIterator(__DIR__);
if ($fileinfo->isFile()) {
$fileExt = $fileinfo->getExtension();
if($fileExt=="csv")
{
echo "File found";
}
else
{
echo "File not found";
}
}
?>
Reference:[http://php.net/manual/en/directoryiterator.getextension.php]

delete file called ".html"

I accidentally created a file with no name http://website.com/myFolder/.html,
now, in the control panel of my webhost, this file is not listed, I cannot see or delete it...
but I can see it using this "myList.php" file: (http://website.com/myFolder/myList.php):
<?php
echo "<ol>";
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo '<li>'.$entry.'</li>';
}
}
closedir($handle);
}
echo "</ol>";
?>
This "myList.php" file outputs all the files present in the directory: http://website.com/folder/
also the file with no name http://website.com/myFolder/.html
How can I delete this file?
I tried to create another .php file called http://website.com/myFolder/myDelete.php,
and use the php function unlink():
<?php
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
echo ("Error deleting".$path);
}else{
echo ("Deleted".$path);
}
}
}
?>
But it doesn't work.
$path = "../myFolder/.html";
if(file_exists($path)){
if (is_file($path)){
//unlink($path);
if (!unlink($file)){
^^^^^----undefined variable
Why all of that when you could just have
unlink('.html');
? Your unwanted file is in the same directory as your myDelete.php script, so the rest of all that is pointless.
Files and directories that begin with . are considered "hidden" on *nix systems. You can see them with ls -la but not with just ls.
Try changing the $file variable to just be the name of the file ".html". Make sure to use the $file variable for the delete - this is not defined in your example.
$file = ".html";
if ( file_exists( $file ) ){
if ( ! unlink( $file ) ){
echo "Error deleting '$file'" );
} else{
echo "Deleted '$file'";
}
} else {
echo "File '$file' does not exist!";
}
The one comment suggested you use FTP, you should have FTP access to your server then you can simply delete through FTP.

Copy images from one folder to another

My Web application stored in directory of XAMPP/htdocs/projectname/. And I have images(source) & img(destination) folders in above directory.I am writing following line of code to get the copy images from one folder to another. But I get the following Warnnigs: (Warning: copy(Resource id #3/image1.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs) and images are not copied into destination.
<?php
$src = opendir('../images/');
$dest = opendir('../img/');
while($readFile = readdir($src)){
if($readFile != '.' && $readFile != '..'){
if(!file_exists($readFile)){
if(copy($src.$readFile, $dest.$readFile)){
echo "Copy file";
}else{
echo "Canot Copy file";
}
}
}
}
?>
Just a guess (sorry) but I don't believe you can use $src = opendir(...) and $src.$readFile like that. Try doing this:
$srcPath = '../images/';
$destPath = '../img/';
$srcDir = opendir($srcPath);
while($readFile = readdir($srcDir))
{
if($readFile != '.' && $readFile != '..')
{
/* this check doesn't really make sense to me,
you might want !file_exists($destPath . $readFile) */
if (!file_exists($readFile))
{
if(copy($srcPath . $readFile, $destPath . $readFile))
{
echo "Copy file";
}
else
{
echo "Canot Copy file";
}
}
}
}
closedir($srcDir); // good idea to always close your handles
Replace this line in your code, this will work definitely.
if(copy("../images/".$readFile, "../img/".$readFile))
you are giving wrong path ,if path of your file say script.php is "XAMPP/htdocs/projectname/script.php" and images and img both are in "projectname" folder than you should use following values for $srcPath and $destPath,change their values to
$srcPath = 'images/';
$destPath = 'img/';
public function getImage()
{
$Path='image/'; //complete image directory path
$destPath = '/edit_image/';
// makes new folder, if not exists.
if(!file_exists($destPath) || file_exists($destPath))
{
rmdir($destPath);
mkdir($destPath, 0777);
}
$imageName='abc.jpg';
$Path=$Path.$imageName;
$dest=$destPath.$imageName;
if(copy($Path, $dest));
}

move all files in a folder to another?

when moving one file from one location to another i use
rename('path/filename', 'newpath/filename');
how do you move all files in a folder to another folder? tried this one without result:
rename('path/*', 'newpath/*');
A slightly verbose solution:
// 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);
}
Please try this solution, it's tested successfully ::
<?php
$files = scandir("f1");
$oldfolder = "f1/";
$newfolder = "f2/";
foreach($files as $fname) {
if($fname != '.' && $fname != '..') {
rename($oldfolder.$fname, $newfolder.$fname);
}
}
?>
An alternate using rename() and with 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";
}
tried this one?:
<?php
$oldfolderpath = "old/folder";
$newfolderpath = "new/folder";
rename($oldfolderpath,$newfolderpath);
?>
So I tried to use the rename() function as described and I kept getting the error back that there was no such file or directory. I placed the code within an if else statement in order to ensure that I really did have the directories created. It looked like this:
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
if(is_dir($permanentDir)){
echo $permanentDir . ' is a directory';
if(is_dir($tempDir)){
echo $tempDir . ' is a directory';
}else{
echo $tempDir . ' is not a directory';
}
}else{
echo $permanentDir . ' is not a directory';
}
rename($tempDir . "*", $permanentDir);
So when I ran the code again, it spit out that both paths were directories. I was stumped. I talked with a coworker and he suggested, "Why not just rename the temp directory to the new directory, since you want to move all the files anyway?"
Turns out, this is what I ended up doing. I gave up trying to use the wildcard with the rename() function and instead just use the rename() to rename the temp directory to the permanent one.
so it looks like this.
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
rename($tempDir, $permanentDir);
This worked beautifully for my purposes since I don't need the old tmp directory to remain there after the files have been uploaded and "moved".
Hope this helps. If anyone knows why the wildcard doesn't work in the rename() function and why I was getting the error stating above, please, let me know.
Move or copy the way I use it
function copyfiles($source_folder, $target_folder, $move=false) {
$source_folder=trim($source_folder, '/').'/';
$target_folder=trim($target_folder, '/').'/';
$files = scandir($source_folder);
foreach($files as $file) {
if($file != '.' && $file != '..') {
if ($move) {
rename($source_folder.$file, $target_folder.$file);
} else {
copy($source_folder.$file, $target_folder.$file);
}
}
}
}
function movefiles($source_folder, $target_folder) {
copyfiles($source_folder, $target_folder, $move=true);
}
try this:
rename('path/*', 'newpath/');
I do not see a point in having an asterisk in the destination
If the target directory doesn't exist, you'll need to create it first:
mkdir('newpath');
rename('path/*', 'newpath/');
As a side note; when you copy files to another folder, their last changed time becomes current timestamp. So you should touch() the new files.
... (some codes for directory looping) ...
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
$filetimestamp = filemtime($source.$file);
touch($destination.$file,$filetimestamp);
}
... (some codes) ...
Not sure if this helps anyone or not, but thought I'd post anyway. Had a challenge where I has heaps of movies I'd purchased and downloaded through various online stores all stored in one folder, but all in their own subfolders and all with different naming conventions. I wanted to move all of them into the parent folder and rename them all to look pretty. all of the subfolders I'd managed to rename with a bulk renaming tool and conditional name formatting. the subfolders had other files in them i didn't want. so i wrote the following php script to, 1. rename/move all files with extension mp4 to their parent directory while giving them the same name as their containing folder, 2. delete contents of subfolders and look for directories inside them to empty and then rmdir, 3. rmdir the subfolders.
$handle = opendir("D:/Movies/");
while ($file = readdir($handle)) {
if ($file != "." && $file != ".." && is_dir($file)) {
$newhandle = opendir("D:/Movies/".$file);
while($newfile = readdir($newhandle)) {
if ($newfile != "." && $newfile != ".." && is_file("D:/Movies/".$file."/".$newfile)) {
$parts = explode(".",$newfile);
if (end($parts) == "mp4") {
if (!file_exists("D:/Movies/".$file.".mp4")) {
rename("D:/Movies/".$file."/".$newfile,"D:/Movies/".$file.".mp4");
}
else {
unlink("D:/Movies/".$file."/".$newfile);
}
}
else { unlink("D:/Movies/".$file."/".$newfile); }
}
else if ($newfile != "." && $newfile != ".." && is_dir("D:/Movies/".$file."/".$newfile)) {
$dirhandle = opendir("D:/Movies/".$file."/".$newfile);
while ($dirfile = readdir($dirhandle)){
if ($dirfile != "." && $dirfile != ".."){
unlink("D:/Movies/".$file."/".$newfile."/".$dirfile);
}
}
rmdir("D:/Movies/".$file."/".$newfile);
}
}
unlink("D:/Movies/".$file);
}
}
i move all my .json files from root folder to json folder with this
foreach (glob("*.json") as $filename) {
rename($filename,"json/".$filename);
}
pd: someone 2020?

Categories