Deleting contents of all folders - php

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);
}

Related

How to match image name with database record?

I've got the following problem:
I have some images in a folder and a sql database record.I have to fetch all images from folder and we have to match that image name with having the field in the database. If these are same then we have to rename that image with the another name. How would I do that?
<?php
$query = "Select ITCFields.ImageID,UDFields.Zoho_ID from ITCFields,UDFields where
ITCFields.ImageID='1234899'";
$resa = odbc_exec($conn,$query);
echo "<table border='1'>
<tr>
<th>ZohoID</th>
<th>Image</th>
<th>Full_Name</th>
</tr>";
while( $row = odbc_fetch_array($resa) ) {
echo "<tr>";
$zoho_id=$row['Zoho_ID'];
$image_id=$row['ImageID'];
echo "<td>" .$zoho_id."</td>";
echo "<td>" .$image_id."</td>";
$full_name=$zoho_id.'_'.$image_id.'.jpg';
echo "<td>" .$full_name."</td>";
echo "</tr>";
}
odbc_close($conn);
?>
<?php
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");
if (!file_exists(IMAGE_File_Path_Modified)) {
mkdir(IMAGE_File_Path_Modified, 0777, true);
}
$srcdire=opendir($srcdir);
while($readFile = readdir($srcdire))
{
if($readFile != '.' && $readFile != '..')
{
if (!file_exists($readFile))
{
if(copy($srcdir . $readFile, $destdir . $readFile ))
{
echo "Copy file";
}
else
{
echo "Canot Copy file";
}
}
}
}
closedir($srcdir);
?>
<?php
$directory=constant("IMAGE_File_Path_Modified");
if ($dir = opendir($directory) )
{
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
}
}
closedir($dir);
}
foreach($images as $image) {
echo $image."</br>";
}
?>
Please Help me to sought out it.
Is image name very important in your code logic?
Usually the problem of having duplicate images is solved by hashing the image name to a unique name (for example with the unix date time value) when it is uploaded and using that name for all further logic. So the unique name for the name becomes the hashed name and you can still use the original name to display if required as another field in the table.
So the problem essentially becomes that of giving each image a unique name then to track if it is unique.
Below is the code of uploading the image.
function uploadImage($image,$path,$thumbpath)
{
if($image!=''){
$explode=explode('.',$_FILES[$image]['name']);
$file=time().'.'.$explode[1];
$file_tempname=$_FILES[$image]['tmp_name'];
move_uploaded_file($file_tempname,$path.$file);
createThumb($path.$file,$thumbpath.$file, 80, 80);
}
return $file;
}
first of all fetch all the folder images name than match with your db images name.
$dir = "/images/";
$img_name = scandir($dir);
while( $row = odbc_fetch_array($resa) ) { echo "";
$zoho_id=$row['Zoho_ID'];
$image_id=$row['ImageID'];
echo "" .$zoho_id."";
echo "" .$image_id."";
$full_name=$zoho_id.'_'.$image_id.'.jpg';
if(in_array($full_name,$img_name)){
//do your chanes
}
echo "" .$full_name."";
}

copy one directory to another in php

<?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.

Variable Syntax in PHP

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;
...

Scanning folder for files instead of array

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;
}
?>

return in function not working but echo works in PHP

i have the following function when i try and return the vaule its only shows 1 folder but when i echo the function it show the correct informaion.
PHP Code:
$FolderList = "";
function ListFolder($path) {
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList .= ('<option value="">'.$path.'</option>');
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
//Display a list of sub folders.
ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList; //ERROR: Only Shows 1 Folder
echo $FolderList; //WORKS: Show All The Folders Correctly
}
Thanks
Give this a shot:
function ListFolder($path)
{
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList = ('<option value="">'.$path.'</option>');
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
$FolderList .= ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
echo ListFolder('/path/to/folder/');
I simply changed the $FolderList to be assigned to the return value of the ListFolder function.
Inside your while loop, you're calling ListFolder again. This is okay to do but you're not storing the result anywhere and just echoing the result every time ListFolder is called.
That correct format you're seeing on the page is not that 1 string being echoed at the end. its a single directory being echoed every time ListFolder is being called.
Below is the code that works.
function ListFolder($path)
{
$FolderList = "";
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList .= ('<option value="">'.$path.'</option>');
while (false !== ($file = readdir($dir_handle)))
{
if($file!="." && $file!="..")
{
if (is_dir($path."/".$file))
{
//Display a list of sub folders.
$FolderList .= ListFolder($path."/".$file);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
Each function call has its own variable scope. You need to union the returned value from your recursive call with the one that you’ve gathered in the while loop:
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
$FolderList .= ListFolder($path."/".$file);
}
}
}
You forgot to catch the return value of the function calls
$FolderList .= ListFolder($path."/".$file);
You just add one folder to the string, than call the function, but do nothing with the return value. Then you return $FolderList, which only contains the one entry you add before the while-loop
When *echo*ing it, its just send directly to the browser independently on which level of recursion you are, so you think, that $FolderList is full, but in fact its just every sungle $FolderList from each recursion step.
Alternative Method
function ListFolder($path, &$FolderList = array()) {
$path = str_replace("//","/",$path);
//using the opendir function
$dir_handle = #opendir($path) or die("Unable to open $path");
//Leave only the lastest folder name
$dirname = end(explode("/", $path));
//display the target folder.
$FolderList[] = '<option value="">'.$path.'</option>';
while(false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
//Display a list of sub folders.
ListFolder($path."/".$file, $FolderList);
}
}
}
//closing the directory
closedir($dir_handle);
return $FolderList;
}
$paths = ListFolder(getcwd());
echo "<select>".implode("", $paths)."</select>";

Categories