php rmdir or unlink file from folder - php

The following code deletes the files in a folder uploads.How do I delete the folder as well when a user clicks Delete Folder (or similar).
I tried using rmdir but I am not getting errors only blank move.php file.
What's the correct/recommended way of doing it ? Please advice.
<?php
$actfolder = $_REQUEST['folder'];
require_once("models/config.php");
if(!securePage($_SERVER['PHP_SELF'])){
die();
}
require("models/db-settings.php");
if(isset($_GET['file'])){
$filename = "uploads/$loggedInUser->username$actfolder/" . ltrim($_GET['file'], '/\\');
// make sure only deleting a file in files/ directory
if (dirname(realpath($filename)) == realpath("uploads/$loggedInUser->username$actfolder/")) {
unlink($filename);
}
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>

Just try something like this:
$filename = "uploads/$loggedInUser->username$actfolder/";
if (is_dir($filename) === true)
{
$files = array_diff(scandir($filename), array('.', '..'));
foreach ($files as $file)
{
unlink(realpath($filename) . '/' . $file);
}
rmdir($filename); //remove directory
}

Related

PHP Remove all Files From a Directory - Exclude File Extension

I am trying for the life of me to find the best way to delete all files in a single directory excluding a single file extension, ie anything that is not .zip
The current method I have used so far which successfully deletes all files is:
$files = glob('./output/*');
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
I have tried modifying this like so:
$files = glob('./output/**.{!zip}', GLOB_BRACE);
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
However, I am not hitting the desired result. I have changed the line as follows which has deleted only the zip file itself (so I can do the opposite of desired).
$files = glob('./output/*.{zip}', GLOB_BRACE);
I understand that there are other methods to read directory contents and use strpos/preg_match etc to delete accordingly. I have also seen many other methods, but these seem to be quite long winded or intended for recursive directory loops.
I am certainly not married to glob(), I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
Any help/advice is appreciated.
$exclude = array("zip");
$files = glob("output/*");
foreach($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($extension, $exclude)) unlink($file);
}
This code works by having an array of excluded extensions, it loads up all files in a directory then checks for the extension of each file. If the extension is in the exclusion list then it doesn't get deleted. Else, it does.
This should work for you:
(I just use array_diff() to get all files which are different to *.zip and then i go through these files and unlink them)
<?php
$files = array_diff(glob("*.*"), glob("*.zip"));
foreach($files as $file) {
if(is_file($file))
unlink($file); // delete file
}
?>
How about calling to the shell? So in Linux:
$path = '/path/to/dir/';
$shell_command = escapeshellcmd('find ' . $path .' ! -name "*.zip" -exec rm -r {}');
$output = shell_exec($shell_command);
I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
SPL Iterators are very effective and efficient.
This is what I would use:
$folder = __DIR__;
$it = new FilesystemIterator($folder, FilesystemIterator::SKIP_DOTS);
foreach ($it as $file) {
if ($file->getExtension() !== 'zip') {
unlink($file->getFilename());
}
}
Have you tried this:
$path = "dir/";
$dir = dir($path);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && substr($file, -4) !== '.zip') {
unlink($file);
}
}

PHP copy all images folder from one folder to another

I am working on some code that will take all the images in one folder and copy them into another folder and then delete the original folder and it content.
I have:
copy('images/old-folder/*', 'images/new-folder/');
unlink('images/old-folder/');
but this does not work :( but it doesn't work I mean the files dont copy over and the old-folder is not deleted :(
I even tried:
system('cp images/old-folder/* images/new-folder/');
and that didn't work either :( Please help.
I have even tried to change the permissions of the two folders:
chmod('images/old-folder/', 0777);
chmod('images/new-folder/', 0777);
foreach(glob('images/old-folder/*') as $image) {
copy($image, 'images/new-folder/' . basename($image)); unlink($image);
}
rmdir('images/old-folder');
check the docs: glob, rmdir, also you might find user comments on rmdir useful.
EDIT:
added basepath to the second parameter to the copy function which has to be an actual path and not a directory.
<?php
$src = 'pictures';
$dst = 'dest';
$files = glob("pictures/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
}
?>
Found here: PHP copy all files in a directory to another?
Here is a modified version from #Prasanth that should work (not tested)
<?php
$oldfolder = 'images/new-folder';
$newfolder = 'images/old-folder';
$files = glob($oldfolder . '/*');
foreach($files as $file){
$filename = basename($file);
copy($file, $oldfolder . '/' . $filename);
unlink($file);
}
rmdir($oldfolder);
?>

PHP rename folder in directory

How can i get $filename to be one specific path? Not a specific folder?
I want to rename several folders in folder named output.
I tried this:
$fileName = '/path/folder/output';
Here is my original code:
<?php
$fileName = '351437-367628';
$newNametemp = explode("-",$fileName);
if(is_array($newNametemp)){
$newName = $newNametemp[0];
print_r($newName); // lar navnet stå att etter første bindestrek
rename($fileName, $newName);
}
?>
$file_path = "uploads/";
$input = $_POST['name_of _the_folder_You WIsh']; // this is the new folder you'll create
$file_path .= $input . '/';
if (!file_exists($file_path)) {
mkdir($file_path);
}
chmod($file_path, 0777);
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
Here is a sample script that does (I think) what you're looking for. It loops through a directory, renaming all subdirectories.
Save code to demo.php, and chmod +x demo.php && ./demo.php.
If you'd prefer an object-oriented approach, or need any changes let me know and I'll modify the code.
#!/usr/bin/php
<?php
//root directory
$outputDir = '/path/folder/output';
//get all subdirectories in the root directory
$dirs = scandir($outputDir);
if ($dirs === FALSE) {
echo "scandir() failed.\n";
exit(1);
}
//loop through each subdirectory and rename.
foreach($dirs as $dir) {
$newName = "${dir}.tmp"; //rename as needed; here we append ".tmp" to the subdirectory.
$success = rename($dir, $newName);
if (!$success)
echo "Rename of $dir failed.\n"; //there was an error during rename, handle it.
}

PHP Delete all folder content without deleting root folder

I'm trying to delete the content of a folder with PHP. This folder has subfolders and files. I want to delete all but the root folder.
For example:
FolderFather
--Folderchild1
--FolChild2
----SubFolChild2
------Anotherfile.jpg
--MyFile.jpg
I want remove all folder except root directory Folder.
Something like
function empty_dir($directory, $delete = false)
{
$contents = glob($directory . '*');
foreach($contents as $item)
{
if (is_dir($item))
empty_dir($item . '/', true);
else
unlink($item);
}
if ($delete === true)
rmdir($directory);
}
should work.
E.g. empty_dir('/some/path/'); should empty that directory without removing,
empty_dir('/some/path/', true); should empty and than remove the directory.
Try:
function deleteAll($path)
{
$dir = dir($path);
while ($file = $dir->read())
{
if ($file == '.' || $file == '..') continue;
$file = $path . '/' . $file;
if (is_dir($file))
{
deleteAll($file);
rmdir($file);
}
else
{
unlink($file);
}
}
}
Calling deleteAll('/path/to/FolderFather'); should work as expected.
You can use scandir() for directory contents and unlink() for deleting contents.
<?php
$dir = "/yourfolder";
$dir_contents = scandir($dir);
foreach($dir_contents as $content)
{
unlink($dir.'/'.$content);
}
$contents = glob('path/*'); // to get all the contents
foreach ($contents as $file) { // loop the files
if (is_file($file)) {
unlink($file); //------- delete the file
}
}

how to delete a file from folder in php

I have a folder 'items' in which there are 3 files item1.txt, item2.txt and item3.txt.
I want to delete item2.txt file from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($file);
}
}
closedir($dirHandle);
?>
Initially the folder should have 777 permissions
$data = "item2.txt";
$dir = "items";
while ($file = readdir($dirHandle)) {
if ($file==$data) {
unlink($dir.'/'.$file);
}
}
or try
$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);
No need of while loop here for just deleting a file, you have to pass path of that file to unlink() function, as shown below.
$file_to_delete = 'items/item2.txt';
unlink($file_to_delete);
Please read details of unlink() function
http://php.net/manual/en/function.unlink.php
There is one bug in your code, you haven't given the correct path
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($dir."/".$file);//give correct path,
}
}
closedir($dirHandle);
?>
unlink
if($file==$data) {
unlink( $dir .'/'. $file);
}
It's very simple:
$file='a.txt';
if(unlink($file))
{
echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}
//if file is in other folder then do as follows
unlink("foldername/".$file);
try renaming it to the trash or a temp folder that the server have access **UNLESS IT'S sensitive data.
rename($old, $new) or die("Unable to rename $old to $new.");

Categories