<?php
extract($_REQUEST);
if(isset($_POST['submit']))
{
$get_folder = $_POST['url'];
$q = mysql_query("insert into test (url) values ('$url')");
if($q)
{
copydir("test",$get_folder);
function copydir($source,$destination)
{
if(!is_dir($destination))
{
$oldumask = umask(0);
mkdir($destination, 01777);
umask($oldumask);
}
$dir_handle = #opendir($source) or die("Unable to open");
while ($file = readdir($dir_handle))
{
if($file!="." && $file!=".." && !is_dir("$source/$file")) //if it is file
copy("$source/$file","$destination/$file");
if($file!="." && $file!=".." && is_dir("$source/$file")) //if it is folder
copydir("$source/$file","$destination/$file");
}
closedir($dir_handle);
}
}
}
?>
this is my code ...it shows Fatal error: Call to undefined function copydir() in C:\xampp\htdocs\mywork\creating-folder\1.php on line 14. But when i copy from copydir("test",$get_folder); to closedir($dir_handle); in separate file it works perfectly but instead of $get_folder need to give some static name
Use copy().
Note that this function does support directories out of the box. A function from one of the comments on the linked documentation page might help:
<?php
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
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);
}
?>
// Will copy foo/test.php to bar/test.php
// overwritting it if necessary
copy('foo/test.php', 'bar/test.php');
This works:
foo();
function foo() { ... }
This won't:
if (...) {
foo();
function foo() { ... }
}
This will:
if (...) {
function foo() { ... }
foo();
}
In general, you're required to declare the function before you call it. The exception is with plain, globally defined functions as in the first example; those are being handled right in the parsing step before execution. Since your function declaration is inside an if statement and thereby conditional, the if condition and thereby the whole code need to be evaluated first. And while the code is being evaluated, you're trying to call a function which hasn't been declared yet.
Related
I have a table with the names of all the folders I wish to delete the contents off. Now I have a script which will delete the entire contents of a folder that I set. Now I though I could put that code in a while loop and it would delete the contents of all the folders. However, I get an error. Here is the code, error is at the bottom, what's going wrong and how do I fix this?
$query = "SELECT * FROM gemeentes";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$gemeente1 = str_replace(" ","",$row['gemeente']);
$gemeente2 = strtolower($gemeente1);
$gemeente3 = str_replace("(","-",$gemeente2);
$gemeente4 = str_replace(")","",$gemeente3);
$gemeente5 = str_replace(",","",$gemeente4);
if(isset($_POST['GO'])) {
$directory = "../subdomains/".$gemeente5."/httpdocs/";
echo $directory;
define('PATH', $directory);
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
else
unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
}
closedir($mydir);
}
destroy(PATH);
echo 'all done.';
}
}
The first delete comes back fine, the second won't do the trick anymore:
../subdomains/aaenhunze/httpdocs/all done.../subdomains/aalburg/httpdocs/
Fatal error: Cannot redeclare destroy() (previously declared in /vhosts/url.nl/httpdocs/deletecontent.php:50) in /vhosts/url.nl/httpdocs/deletecontent.php on line 50
Why are you calling your function as destroy(PATH); with a "define"d constant instead of just the actual underlying variable as: destroy($directory);? Once you take the function out of the loop as Bulk suggested, this should work I'd think...
You are defining the destroy function inside the outermost while loop, so the second time it comes to run the loop the function is already defined. Move the function definition to outside of the while loop to fix this.
Thank you all for the help. I took a look at all your answers and what OzgurH suggested did the trick. The working code:
$query = "SELECT * FROM gemeentes";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$gemeente1 = str_replace(" ","",$row['gemeente']);
$gemeente2 = strtolower($gemeente1);
$gemeente3 = str_replace("(","-",$gemeente2);
$gemeente4 = str_replace(")","",$gemeente3);
$gemeente5 = str_replace(",","",$gemeente4);
if(isset($_POST['GO'])) {
$directory = "../subdomains/".$gemeente5."/httpdocs/";
echo $directory;
destroy($directory);
echo 'all done.';
}
}
function destroy($dir) {
$mydir = opendir($dir);
while(false !== ($file = readdir($mydir))) {
if($file != "." && $file != "..") {
chmod($dir.$file, 0777);
if(is_dir($dir.$file)) {
chdir('.');
destroy($dir.$file.'/');
rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
else
unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
}
}
closedir($mydir);
}
as you can see from my code below I have set a variable ($query) equal to the data posted from an outside form. Under that I tested the variable by echoing it, so the variable seems to be established correctly.
The problem is that near the bottom I'm trying to create another variable, called $str_to_find, where I want it set to output my original variable, $query. However, when I view the output, nothing shows up at all after the code processes this variable near the bottom of my code. I dont' understand why it wouldn't display output.
<?php
$query = $_POST['query'];
echo "$query";
find_files('.');
function find_files($seed) {
if(! is_dir($seed)) return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs)))
{
if($dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if(is_dir($path)) {
$dirs[] = $path;
}
else {
if(preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) {
check_files($path);
}
}
}
closedir($dh);
}
}
}
function check_files($this_file) {
$str_to_find = $query;
if(!($content = file_get_contents($this_file))) {
echo("<p>Could not check $this_file</p>\n");
}
else {
if(stristr($content, $str_to_find)) {
echo("<p>$this_file -> contains $str_to_find</p>\n");
}
}
unset($content);
}
?>
UPDATED CODE
<?php
$query = $_POST['query'];
find_files('.');
function find_files($seed)
{
if(! is_dir($seed)) return false;
$files = array();
$dirs = array($seed);
while(NULL !== ($dir = array_pop($dirs)))
{
if($dh = opendir($dir))
{
while( false !== ($file = readdir($dh)))
{
if($file == '.' || $file == '..') continue;
$path = $dir . '/' . $file;
if(is_dir($path)) { $dirs[] = $path; }
else { if(preg_match('/^.*\.(php[\d]?|js|txt)$/i', $path)) { check_files($path); }}
}
closedir($dh);
}
}
}
function check_files($this_file)
{
$query = $_POST['query'];
$str_to_find = $query;
if(!($content = file_get_contents($this_file))) { echo("<p>Could not check $this_file</p>\n"); }
else { if(stristr($content, $str_to_find)) { echo("<p>$this_file -> contains
$str_to_find</p>\n"); }}
unset($content);
}
?>
This is an issue of scoping. Your $query variable (and indeed any variables not instantiated directly within the function body) is not available within check_files.
You should pass $query in as a parameter to the function.
function check_files($this_file, $query) {
// ...
}
Another options exists to make the variables 'global', however this is seldom a sensible idea.
The reason it's not working is because $query is out of the function's scope. If you want to use a variable declared outside of a function inside of it, you either need to pass it through as a parameter, or use
function check_files($this_file) {
global $query;
$str_to_find = $query;
Although passing it through as a parameter is preferred to using global.
The variable $query is declared outside the function check_files() scope. If you want to access it, put global $query; at the beginning of the function.
You need to declare the the $query global as per the PHP manual, if not, the parser will assume that $query is a local scope variable (local as in "only within this function")
function check_files($this_file) {
global $query;
$str_to_find = $query;
...
I wrote recursive PHP function for folder deletion. I wonder, how do I modify this function to delete all files and folders in webhosting, excluding given array of files and folder names (for ex. cgi-bin, .htaccess)?
BTW
to use this function to totally remove a directory calling like this
recursive_remove_directory('path/to/directory/to/delete');
to use this function to empty a directory calling like this:
recursive_remove_directory('path/to/full_directory',TRUE);
Now the function is
function recursive_remove_directory($directory, $empty=FALSE)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
}elseif(!is_readable($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}else{
// we open the directory
$handle = opendir($directory);
// and scan through the items inside
while (FALSE !== ($item = readdir($handle)))
{
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..')
{
// we build the new path to delete
$path = $directory.'/'.$item;
// if the new path is a directory
if(is_dir($path))
{
// we call this function with the new path
recursive_remove_directory($path);
// if the new path is a file
}else{
// we remove the file
unlink($path);
}
}
}
// close the directory
closedir($handle);
// if the option to empty is not set to true
if($empty == FALSE)
{
// try to delete the now empty directory
if(!rmdir($directory))
{
// return false if not possible
return FALSE;
}
}
// return success
return TRUE;
}
}
Try something like this:
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('%yourBaseDir%'),
RecursiveIteratorIterator::CHILD_FIRST
);
$excludeDirsNames = array();
$excludeFileNames = array('.htaccess');
foreach($it as $entry) {
if ($entry->isDir()) {
if (!in_array($entry->getBasename(), $excludeDirsNames)) {
try {
rmdir($entry->getPathname());
}
catch (Exception $ex) {
// dir not empty
}
}
}
elseif (!in_array($entry->getFileName(), $excludeFileNames)) {
unlink($entry->getPathname());
}
}
I'm using this function to delete the folder with all files and subfolders:
function removedir($dir) {
if (substr($dir, strlen($dir) - 1, 1) != '/')
$dir .= '/';
if ($handle = opendir($dir)) {
while ($obj = readdir($handle)) {
if ($obj != '.' && $obj != '..') {
if (is_dir($dir . $obj)) {
if (!removedir($dir . $obj))
return false;
}
else if (is_file($dir . $obj)) {
if (!unlink($dir . $obj))
return false;
}
}
}
closedir($handle);
if (!#rmdir($dir))
return false;
return true;
}
return false;
}
$folder_to_delete = "folder"; // folder to be deleted
echo removedir($folder_to_delete) ? 'done' : 'not done';
Iirc I got this from php.net
You could provide an extra array parameter $exclusions to recursive_remove_directory(), but you'll have to pass this parameter every time recursively.
Make $exclusions global. This way it can be accessed in every level of recursion.
I have this code:
<?php
$allowed = array('file1', 'file2', 'file3');
if (in_array($_GET["url"], $allowed)) {
// You can include
} else {
// Error message and dont include
}
?>
But instead of writing all the filenames in the array, how can i do so that the files in for example my folder FILES/ is accepted an no other files. How to do that?
Use the file_exists function like this:
if (file_exists('FILES/'.basename($_GET["url"]))) {
// You can include
} else {
// Error message and dont include
}
Function to retrieve files in a folder:
<?
function fGetFilesInFolder($sFolder) {
$aFiles = array();
if(file_exists($sFolder)) {
if ($handle = opendir($sFolder)) {
while (false !== ($sFile = readdir($handle))) {
if ($sFile != "." && $sFile != "..") $aFiles[] = $sFile;
}
closedir($handle);
}
}
return $aFiles;
}
?>
I am trying to delete a folder using this script :
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
Delete('tmp');
It works in my Xampp server, but not on my webserver. I have changed the permissions of the folder and of the file it contains to 0777. So it should be writable(or in this case erasable) but nothing happens. I have even tryied giving the absolute path of the folder as the parameter of the function, but still nothing.Any ideas?
Use this :
function delTree($dir)
{
$files = glob( $dir . '*', GLOB_MARK );
foreach( $files as $file
{
if( is_dir( $file ) )
delTree( $file );
else
#unlink( $file );
}
if( is_dir($dir) ) rmdir( $dir );
};
Does it return false? Or it returns true but doesn't actually remove?
Normally I'd just guess it's a permissions problem.
Try making a folder with mkdir from PHP so PHP is the owner (so to speak) and try to remove that with your function.
If it works, it's a permissions/owner issue.
You can Try this code
<?php
$files = glob('application/*'); foreach($files as $file){ if(is_file($file)) unlink($file); }
?>
Or,
function viewDir($path) {
return is_file($path) ?
#unlink($path) :
array_map(__FUNCTION__, glob($path.'/*')) == #rmdir($path);
}
$dir=$_SERVER["DOCUMENT_ROOT"]."/xxxx/xxxx";
echo $dir;
viewDir($dir);
May be some files are opened using php like fopen and that time it will not delete the folder or directory. I have faced the same issue when I tried to delete a file/folder
Try something like this.
<?php
function delete_directory($target) {
if (is_dir($target))
$dir_handle = opendir($target);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($target.'/'.$file);
}
}
closedir($dir_handle);
rmdir($target);
return true;
}
?>
Hope this helps.
Try this line of code to delete a folder or folder files
I hope this will help you
function deleteAll($str) {
if (is_file($str)) {
return unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
$this->deleteAll($path);
}
return #rmdir($str);
}
}