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;
...
Related
i create this function for search resume file from directory, if resume is available then function return full path, problem is function return nothing if i use "return", if i use "echo" then it will print right path
function search_resume($resume,$dir="uploads/resumes")
{
$root = scandir($dir);
foreach($root as $value)
{
/* echo $value."<br/>"; */
if($value === '.' || $value === '..') {continue;}
if(is_file("$dir/$value"))
{
if($value==$resume)
{
$path="$dir/$value";
return $path;
}
}
else
{
search_resume($resume,"$dir/$value");
}
}
}
A very typical, basic problem with recursive functions: you need to return recursive calls as well, they're not going to return themselves.
...
else {
$path = search_resume($resume,"$dir/$value");
if ($path) {
return $path;
}
}
<?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.
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);
}
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'm looping over all the files in a directory. Now I want to get all the functions and classes defined in each of them. From there, I can examine them further using the ReflectionClass. I can't figure out how to get all the functions and classes defined in a file though.
ReflectionExtension looks the closest to what I want, except my files aren't part of an extension. Is there some class or function I'm overlooking?
Great question. get_declared_classes and get_defined_functions could be a good starting point. You would have to take note of what classes / functions are already defined when trying to determine what's in a given file.
Also, not sure what your end goal is here, but tools such as PHP Depend or PHP Mess Detector may do something similar to what you want. I'd recommend checking them out as well.
This is the best I could come up with (courtesy):
function trimds($s) {
return rtrim($s,DIRECTORY_SEPARATOR);
}
function joinpaths() {
return implode(DIRECTORY_SEPARATOR, array_map('trimds', func_get_args()));
}
$project_dir = '/path/to/project/';
$ds = array($project_dir);
$classes = array();
while(!empty($ds)) {
$dir = array_pop($ds);
if(($dh=opendir($dir))!==false) {
while(($file=readdir($dh))!==false) {
if($file[0]==='.') continue;
$path = joinpaths($dir,$file);
if(is_dir($path)) {
$ds[] = $path;
} else {
$contents = file_get_contents($path);
$tokens = token_get_all($contents);
for($i=0; $i<count($tokens); ++$i) {
if(is_array($tokens[$i]) && $tokens[$i][0] === T_CLASS) {
$i += 2;
$classes[] = $tokens[$i][1];
}
}
}
}
} else {
echo "ERROR: Could not open directory '$dir'\n";
}
}
print_r($classes);
Wish I didn't have to parse out the files and loop over all the tokens like this.
Forgot the former solutions prevents me from using reflection as I wanted. New solution:
$project_dir = '/path/to/project/';
$ds = array($project_dir);
while(!empty($ds)) {
$dir = array_pop($ds);
if(($dh=opendir($dir))!==false) {
while(($file=readdir($dh))!==false) {
if($file[0]==='.') continue;
$path = joinpaths($dir,$file);
if(is_dir($path)) {
$ds[] = $path;
} else {
try{
include_once $path;
}catch(Exception $e) {
echo 'EXCEPTION: '.$e->getMessage().PHP_EOL;
}
}
}
} else {
echo "ERROR: Could not open directory '$dir'\n";
}
}
foreach(get_declared_classes() as $c) {
$class = new ReflectionClass($c);
$methods = $class->getMethods();
foreach($methods as $m) {
$dc = $m->getDocComment();
if($dc !== false) {
echo $class->getName().'::'.$m->getName().PHP_EOL;
echo $dc.PHP_EOL;
}
}
}