Jump to content

Need help unlinking multiple files


eldan88

Recommended Posts

Hey,

 

I am trying to write some code that deletes all the files in a directory and then deletes the directory. The code below pretty much fetches a store ID from all the stores listed below, then it does a mysql fetch array on the store id to find it "store_name" which is the name of the directory, and then the next step is to delete the files and the whole directory. The reason why there is a foreach loop is because I would like to delete the files and folder for multiple stores at the same time.  Below is the code.

<?php require_once("include/database_connection.php");
global $connection;?>


<?php 
if(isset($_POST['submit'])) { 
$store = $_POST['store_id']; // assign the store ID to the $store variable
foreach ($store as $store_id) { // Run a foreach loop to get the store id
$query = "SELECT * FROM stores WHERE store_id = {$store_id} "; // Run the query for the specific store id
$result_query = mysql_query($query,$connection); // Execute the query
$result = mysql_fetch_array($result_query,$connection); // Run a mysql fetch array on the result query 
$store_name = $result['store']; // get the store name
$rmdir = rmdir("store/store_folders/".$store_name); // Delete the directory. 
if(!$rmdir) {
echo $store_name ."Could not be deleted";	
}
	

//$query = "DELETE FROM store_names WHERE store_id = {$store_id} LIMIT 1";
//$result = mysql_query($query,$connection);
//if($result) {echo "Store Deletion Successful";}
}



}

?>

<form action="delete_stores.php" method="post">
<?php
// Following code list all the stores with their checkboxes
$count=1;
$get_all_stores =  "SELECT * FROM stores ";
$query = mysql_query($get_all_stores, $connection);
while($display_store = mysql_fetch_array($query)) {
echo "<input type=\"checkbox\" value=\"{$display_store['store_id']}\" name=\"store_id[]\">" . $count . " " .  $display_store['store_name'] . "</input>" ."<br>";
$count++;}
?>
<input type="submit" name="submit" value="submit">
</form>


Link to comment
Share on other sites

Is Psycho going to reply? Should I wait? Oh, now he's gone...

 

And your question is... why it says the store could not be deleted? You have to delete the files in the folder before you can delete the folder.

 

If you only have files in the folder then

 

array_map("unlink", glob("store/store_folders/" . $store_name ."/*"));
rmdir("store/store_folders/" . $store_name);
should get the job done. Otherwise you'll need something a bit more complicated...

 

This also assumes PHP is allowed to delete the files - you didn't manually upload them yourself or something.

Link to comment
Share on other sites

Is Psycho going to reply? Should I wait? Oh, now he's gone...

 

And your question is... why it says the store could not be deleted? You have to delete the files in the folder before you can delete the folder.

 

If you only have files in the folder then

 

array_map("unlink", glob("store/store_folders/" . $store_name ."/*"));
rmdir("store/store_folders/" . $store_name);
should get the job done. Otherwise you'll need something a bit more complicated...

 

This also assumes PHP is allowed to delete the files - you didn't manually upload them yourself or something.

 

Thanks for your help requinix. Will do a little bit more reading on those functions and apply the code you provided.

Link to comment
Share on other sites

Is Psycho going to reply? Should I wait? Oh, now he's gone...

 

And your question is... why it says the store could not be deleted? You have to delete the files in the folder before you can delete the folder.

 

If you only have files in the folder then

 

array_map("unlink", glob("store/store_folders/" . $store_name ."/*"));
rmdir("store/store_folders/" . $store_name);
should get the job done. Otherwise you'll need something a bit more complicated...

 

This also assumes PHP is allowed to delete the files - you didn't manually upload them yourself or something.

 

Hey requinix. I have tried that and it didn't seem to work. I'm not sure why you would want to use array_map. Do you have any other suggestions?Thanks

Link to comment
Share on other sites

Doesn't seem to work how? It's not like I can see what you're doing.

 

I have done some searching onlline and saw someone who used the following code to get this accomplished..


foreach (glob($dirPath."*.*") as $removeFile)
{
unlink($removeFile);
}

I have a question what does *.* mean?

Link to comment
Share on other sites

Doesn't seem to work how? It's not like I can see what you're doing.

Nevermind! I find out that the * represents a wildcard!... I figured out that I can unlink the files using the following

 

foreach (glob($dirPath."*.*") as $removeFile)

{

unlink($removeFile);

 

foreach (glob("php_files/*.*") as $removeFile)

{

$unlink = unlink($removeFile);

}

if(!$unlink) {"Files could not be deleted";}

 

 

 

Is it good programming practice  to add that foreach inside an existing for each statment that i have (below)

foreach ($store as $store_id) { // Run a foreach loop to get the store id
$query = "SELECT * FROM stores WHERE store_id = {$store_id} "; // Run the query for the specific store id
$result_query = mysql_query($query,$connection); // Execute the query
$result = mysql_fetch_array($result_query,$connection); // Run a mysql fetch array on the result query 

// Im going to add the foreach loop that unlinks all files in the directory over here below this
}
Link to comment
Share on other sites

It's not even a question of practice: you have to put them in there because you don't know what directories to delete until then.

 

By the way, the array_map() I used is functionally equivalent to your foreach loop.

I think your right. I believe used the array_map incorrectly. I will try using  it again.

 

I have one more question. How can I delete all the files in 2 different directories simultaneously based on the code below

$dir_path = "store/stores/".$store_name."/*.*"; // Set the directory path with the dir path variable. use the wild card to delete ALL the files in the directory


$dir_path2 = store_front_end/stores/".$store_name."/*.*"; // How can I unlink all these files along with $dir path???


foreach (glob($dir_path) as $removeFile) // Find all the files in the directory of the store_name
{$unlink = unlink($removeFile);}//Unlink all the files in the store_name directory
if(!$unlink)
Link to comment
Share on other sites

I just want to comment upon this bit:

Is it good programming practice  to add that foreach inside an existing for each statment that i have (below)

foreach ($store as $store_id) { // Run a foreach loop to get the store id
$query = "SELECT * FROM stores WHERE store_id = {$store_id} "; // Run the query for the specific store id
$result_query = mysql_query($query,$connection); // Execute the query
$result = mysql_fetch_array($result_query,$connection); // Run a mysql fetch array on the result query 

// Im going to add the foreach loop that unlinks all files in the directory over here below this
}

 

While it is true that using a loop inside another is required at times, there is one thing you never should be using inside loops: SQL queries.

Move that SELECT query outside of the loop, concatenate all of the IDs of shops to delete, and then use a "WHERE id IN()" condition to fetch all rows in one query. In short, this is how your code should look, roughly:

// Create the sprintf () template for the SQL query.
$SQL = "SELECT {$Fields} FROM `stores` WHERE `store_id` IN(%s)";

// Make sure all of the values we're sending to the query are integers.
// (Protection against SQL injections.)
$storeIDs = array_map ("intval", $store);

// Implode the array of IDs into a comma-delimited string, and add to SQL query.
$SQL = sprintf ($SQL, implode (',', $storeIDs));

// Execute the query, and handle any potential SQL errors.
if (!$res = DB->query ($SQL)) {
    trigger_error ("Could not retrieve shops!", E_USER_ERROR);
}

// Loop through all of the shops returned from the query.
while ($row = $res->fetch_array ()) {
    // Delete the folders here.
}
This way you only try to delete shops that you actually have in your database, and you're saving a whole lot of server resources from cutting down on the number of SQL queries you need to do.

 

PS: I suspect you should be looking into JOINs as well.

Link to comment
Share on other sites

You can't do it simultaneously. Use two loops like you showed.

 

requinix. I actually used the array_map, and it worked. However, for some reason its not unlinking the files of my second directory. I'm not sure why. Is there anyway to debug that to see why its not unlinking  the files in my directory?

Link to comment
Share on other sites

I just want to comment upon this bit:

 

While it is true that using a loop inside another is required at times, there is one thing you never should be using inside loops: SQL queries.

Move that SELECT query outside of the loop, concatenate all of the IDs of shops to delete, and then use a "WHERE id IN()" condition to fetch all rows in one query. In short, this is how your code should look, roughly:

// Create the sprintf () template for the SQL query.
$SQL = "SELECT {$Fields} FROM `stores` WHERE `store_id` IN(%s)";

// Make sure all of the values we're sending to the query are integers.
// (Protection against SQL injections.)
$storeIDs = array_map ("intval", $store);

// Implode the array of IDs into a comma-delimited string, and add to SQL query.
$SQL = sprintf ($SQL, implode (',', $storeIDs));

// Execute the query, and handle any potential SQL errors.
if (!$res = DB->query ($SQL)) {
    trigger_error ("Could not retrieve shops!", E_USER_ERROR);
}

// Loop through all of the shops returned from the query.
while ($row = $res->fetch_array ()) {
    // Delete the folders here.
}
This way you only try to delete shops that you actually have in your database, and you're saving a whole lot of server resources from cutting down on the number of SQL queries you need to do.

 

PS: I suspect you should be looking into JOINs as well.

 

 

Thank you for the tip!

 

Is the code example you stated object oriented?

Link to comment
Share on other sites

Yes, and no. The code snippet itself is too short, and too specific to be object-oriented on its own. That's not to say that it can be used in some object-oriented code. OOP is more of a design philosophy for an entire project, than for a small code snippet.

My advice is to just focus on the basics of PHP and programming for now, and then start to look at OOP once you've gotten a solid understanding of the fundamentals down.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.