copy file from one folder to other - php

I want to move all files from one folder to other. my code is as following. in this I made a folder in which i want to copy all file from templats folder
$doit = str_replace(" ", "", $slt['user_compeny_name']);
mkdir("$doit");
$source = "templat/";
$target = $doit . "/";
$dir = opendir($source);
while (($file = readdir($dir)) !== false) {
copy($source . $file, $target . $file);
}
It working fine . copy all files but give warning that The first argument to copy() function cannot be a directory
can any one help me asap

Readdir will read all children in a directory, including other dirs, and 'virtual' dirs like . and .. (link to root and parent dir, resp.) You'll have to check for these and prevent the copy() function for these instances.
while (($file = readdir($dir)) !== false)
{
if(!is_dir($file))
{
copy($source.$file, $target.$file);
}
}

You are not accounting for the . and the .. files at the top of the directory. This means that the first thing it tries to copy is "\template." which would be the same as trying to copy the directory.
Just add something like:
if ($file !== "." && $file !== "..")
...

opendir() will include items . and .. as per the documentation.
You will need to exclude these by using the code in the other comments.

if ($file != "." && $file != "..") {
// copy
}

I know, this question is pretty old, but also are the answers. I feel the need to show some new methods, which can be used to execute the requested task.
In the mean time Objects were introduced with a lot more features and possibilities. Needless to say, the other answers will still work aswell.
But here we go, using the DirectoryIterator:
$szSrcFolder = 'source_folder';
$szTgtFolder = 'target_folder';
foreach (new DirectoryIterator($szSrcFolder) as $oInfo)
if ($oInfo->isFile())
copy($oInfo->getPathname(), $szTgtFolder . DIRECTORY_SEPARATOR . $oInfo->getBasename());
Remember, within this script, all paths are relative to the working directory of the script itself.
I think it is self explaining, but we will take a look. This few lines will iterate over the whole content of the source folder and check if it is a file and will copy it to the target folder, keeping the original file name.

Related

List files in same directory using PHP

I'm trying to list files in a folder. I have done this before, so I am not sure why I am having a problem now.
I have a PDF files I am trying to display to my web page. The directory structure looks like this:
folder1/folder2/displayFiles.php
folder1/folder2/files.pdf
displayFiles.php is the process file where I am using the code below.
I am trying to display the file called files.pdf onto the page, which is in the same directory as the process file.
Here is my code so far:
<?php
$dir = "folder1/folder2/";
// $dir = "/"; <-- I also tried this
$ffs = scandir($dir);
foreach($ffs as $ff)
{
if($ff != '.' && $ff != '..')
{
$filesize = filesize($dir . '/' . $ff);
echo "<ul><li><a download href='$dir/$ff'>$ff</a></li></ul>";
}
}
?>
I know it's a simple fix. I just cannot find the code to fix it.
Your $dir is pointing at a non-existent folder
Change the dir to point to the folder correctly $dir = ".";.
Just use glob
http://php.net/manual/de/function.glob.php
$pdfs = glob("*.pdf"); // if needed loop through your directorys and glob files
print_r($pdfs);
Just an example. You should be able to use it with some edits.

PHP delete (.extension) files that are modified after specific time from directory and all sub-directories

I need a little bit of help. I need to write a script that will look through all directories and sub-directories and delete specific extensions that are modified after specific time. I can get it to delete files from specific path, but I need the script to search inside sub directories. Is there any way to do that?
I have tried this for files but I have no idea on how to make it work with directories and sub directories
$path = '/path/to/file/';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
$filelastmodified = filemtime($path . $file);
if( $filelastmodified > "MY TIME STAMP" )
{
unlink($path . $file);
}
echo "deleted";
}
closedir($handle);
}
Create a recursive function, if it finds a folder it calls itself passing the folder name.

PHP Move Files With Specific Format vs Move All Files

I have these files in /public_html/ directory :
0832.php
1481.php
2853.php
3471.php
index.php
and I want to move all those XXXX.php (always in 4 digits format) to directory /tmp/, except index.php. how to do it with reg-ex and loop?
Alternatively, how about moving all files (including index.php) first to /tmp/ then later on put only index.php back to /public_html/, which one you think is less CPU consuming?
Last thing, I found this tutorial to move file using PHP: http://www.kavoir.com/2009/04/php-copying-renaming-and-moving-a-file.html
But how to move ALL files in a directory?
You can use FilesystemIterator with RegexIterator
$source = "FULL PATH TO public_html";
$destination = "FULL PATH TO public_html/tmp";
$di = new FilesystemIterator($source, FilesystemIterator::SKIP_DOTS);
$regex = new RegexIterator($di, '/\d{4}\.php$/i');
foreach ( $regex as $file ) {
rename($file, $destination . DIRECTORY_SEPARATOR . $file->getFileName());
}
The best way would be to do it directly via the file system, but if you absolutely have to do it with PHP, something like this should do what you want - you'll have to change the paths so that they are correct, obviously. Note that this assumes that there could be other files in the public_html directory, and so it only get the filenames with 4 numbers.
$d = dir("public_html");
while (false !== ($entry = $d->read())) {
if($entry == '.' || $entry == '..') continue;
if(preg_match("#^\d{4}$#", basename($entry, ".php")) {
// move the file
rename("public_html/".$entry, "/tmp/".$entry));
}
}
$d->close();
in fact - I went to readdir manual page and the fist comment to read is:
loop through folders and sub folders with option to remove specific files.
<?php
function listFolderFiles($dir,$exclude){
$ffs = scandir($dir);
echo '<ul class="ulli">';
foreach($ffs as $ff){
if(is_array($exclude) and !in_array($ff,$exclude)){
if($ff != '.' && $ff != '..'){
if(!is_dir($dir.'/'.$ff)){
echo '<li>'.$ff.'';
} else {
echo '<li>'.$ff;
}
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff,$exclude);
echo '</li>';
}
}
}
echo '</ul>';
}
listFolderFiles('.',array('index.php','edit_page.php'));
?>
Regexes are in fact overkill for this, as we only need to do some simple string matching:
$dir = 'the_directory/';
$handle = opendir($dir) or die("Problem opening the directory");
while ($filename = readdir($handle) !== false)
{
//if ($filename != 'index.php' && substr($filename, -3) == '.php')
// I originally thought you only wanted to move php files, but upon
// rereading I think it's not what you really want
// If you don't want to move non-php files, use the line above,
// otherwise the line below
if ($filename != 'index.php')
{
rename($dir . $filename, '/tmp/' . $filename);
}
}
Then for the question:
alternatively, how about moving all files (including index.php) first to /tmp/ then later on put only index.php back to /public_html/, which one you think is less CPU consuming?
It could be done, and it would probably be slightly easier on your CPU. However, there are several reasons why this doesn't matter. First off, you're already doing this in a very inefficient way by doing it through PHP, so you shouldn't really be looking at the strain this puts on your CPU at this point unless you are willing to do it outside PHP. Secondly, that would cause more disk access (especially if the source and destination directory aren't on the same disk or partition) and disk access is much, much slower than your CPU.

get all file names from a directory in php

(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}

PHP: How can I grab a single file from a directory without scanning entire directory?

I have a directory with 1.3 Million files that I need to move into a database. I just need to grab a single filename from the directory WITHOUT scanning the whole directory. It does not matter which file I grab as I will delete it when I am done with it and then move on to the next. Is this possible? All the examples I can find seem to scan the whole directory listing into an array. I only need to grab one at a time for processing... not 1.3 Million every time.
This should do it:
<?php
$h = opendir('./'); //Open the current directory
while (false !== ($entry = readdir($h))) {
if($entry != '.' && $entry != '..') { //Skips over . and ..
echo $entry; //Do whatever you need to do with the file
break; //Exit the loop so no more files are read
}
}
?>
readdir
Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.
Just obtain the directories iterator and look for the first entry that is a file:
foreach(new DirectoryIterator('.') as $file)
{
if ($file->isFile()) {
echo $file, "\n";
break;
}
}
This also ensures that your code is executed on some other file-system behaviour than the one you expect.
See DirectoryIterator and SplFileInfo.
readdir will do the trick. Check the exampl on that page but instead of doing the readdir call in the loop, just do it once. You'll get the first file in the directory.
Note: you might get ".", "..", and other similar responses depending on the server, so you might want to at least loop until you get a valid file.
do you want return first directory OR first file? both? use this:
create function "pickfirst" with 2 argument (address and mode dir or file?)
function pickfirst($address,$file) { // $file=false >> pick first dir , $file=true >> pick first file
$h = opendir($address);
while (false !== ($entry = readdir($h))) {
if($entry != '.' && $entry != '..' && ( ($file==false && !is_file($address.$entry)) || ($file==true && is_file($address.$entry)) ) )
{ return $entry; break; }
} // end while
} // end function
if you want pick first directory in your address set $file to false and if you want pick first file in your address set $file to true.
good luck :)

Categories