I've got one problem when I want to delete all files in one directory with Codeigniter..
I've been watching and trying from any tutorials, and just having one problem.. It always can't delete any files.
here's my script :
#view
Delete All File
#controller
public function delete_allfile()
{
$files = glob($_SERVER['DOCUMENT_ROOT'].'upload/perizinan/*'); // get all file names
if(is_dir($path))
{
$this->session->set_flashdata('message',
'
Wrong directory !
');
redirect('sia/perizinan');
}else
{
foreach($files as $file)
{ // iterate files
if(is_file($file))
unlink($file); // delete file
}
redirect('sia/perizinan');
}
}
Try using Codeigniter's file helper for deleting files. It does exactly what you're trying to do. Of course it won't work if the permissions are wrong on the folder (It requires the permission: rwxrwxrwx (0777)), but it makes for a bit cleaner and easier to debug code.
In the controller's constructor add:
$this->load->helper('file');
And replace:
foreach($files as $file)
{ // iterate files
if(is_file($file))
unlink($file); // delete file
}
with
delete_files('./path/to/directory/');
Or if you want to include subfolders recursvively
delete_files('./path/to/directory/', TRUE);
This deletes ALL files in the folder/subfolders so if you want more control you're better off doing it with unlink so you can decide what to delete.
Do you get any error message on the page or in the log file? Have you checked the folder/ files permissions? You can use the chmod and fileperms functions
It's Simple and Easy.. You can Try this.
$files = glob('/home/xxx/public_html/project_name/application/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
It will probably work, I have used
$this->load->helper('directory');
$this->load->helper("file");
$dir_fiels = directory_map('resources/captcha/');
$len = sizeOf($dir_fiels);
for($i=0; $i<$len;$i++){
unlink('resources/captcha/'.$dir_fiels[$i]);
}
Related
I have been working on a project that involves a step, during which the script needs to automatically remove a certain directory in Linux ( and all its contents ).
I am currently using the following code to do that:
# Perform a recursive removal of the obsolete folder
$dir_to_erase = $_SESSION['path'];
function removeDirectory($dir_to_erase) {
$files = glob($dir_to_erase . '/*');
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($dir_to_erase);
return;
}
Where $_SESSION['path'] is the folder to erase. Been working like a charm, but I recently had to add a .htaccess file to the folder, and I noticed the script stopped working correctly ( it keeps removing the rest of the files fine, but not the .htaccess files ).
Can anyone point me as to what I should add to the code include the hidden dot files in the removal process?
simply, you can rely on DirectoryIterator
The DirectoryIterator class provides a simple interface for viewing
the contents of filesystem directories.
function removeDirectory($dir_to_erase) {
$files = new DirectoryIterator($dir_to_erase);
foreach ($files as $file) {
// check if not . or ..
if (!$file->isDot()) {
$file->isDir() ? removeDirectory($file->getPathname()) : unlink($file->getPathname());
}
}
rmdir($dir_to_erase);
return;
}
there are lot of features there you may make use of them, as check the owner which is pretty useful to make sure not to remove critical file.
You can slightly modify your function to remove hidden files also:
function removeDirectory($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir."/".$object))
removeDirectory($dir."/".$object);
else
unlink($dir."/".$object);
}
}
rmdir($dir);
}
}
As per this answer:
PHP glob() doesnt find .htaccess
glob(".*") will find .htaccess
I'm trying to create a function which will run periodically to delete any old "user" folders which don't have an active user. This is the function I have:
function delete_temp_user_files() {
$dir = $_SERVER['DOCUMENT_ROOT'] . "/users/";
$dir_files = array();
$dir_files = scandir($dir);
foreach ($dir_files as $username) {
if ($username == "." || $username == "..") continue;
if (!user_exist($username)) {
$dir1 = $_SERVER['DOCUMENT_ROOT'] . "/users/" . $username;
if (!is_dir($dir1)) continue;
if (file_exists($dir1)) unlink($dir1);
}
}
}
But when it tries to delete the directory I get the error "Warning: unlink(/path/to/users/delete1/): Is a directory in /page.php on line..." I know the directory exists because I can see it in the directory, and it found it using scandir() anyway.
I use unlink to delete these same folders in other scripts and it works fine. The directories aren't empty so I can't user rmdir().
I'm not familiar with permissions or anything like that, is this some kind of issue with that? And do I need to worry about permissions if I only ever use PHP scripts to delete files and folders (like when the user clicks on the delete button which runs the script I wrote)?
UPDATE:
After scouring the web I finally found how to delete a directory and it's not easy lol Add this function into the previous function and it works!
function delete_dir($directory) {
foreach(glob("{$directory}/*") as $file)
{
if(is_dir($file)) {
delete_dir($file);
} else {
unlink($file);
}
}
rmdir($directory);
}
unlink is used to delete files, use rmdir
Please note, you must first delete all files in directory.
Also, your code is very dangerous. Assume with time, you have 100,000 users so will have 100,000 folders. Can you imagine how much time will this line take?
foreach ($dir_files as $username) {
Please think alternate way.
Good way, don't delete users from your database. find users who didn't login since 6 months (say) and disable them. this way, your loop is smaller.
There is a function given on the rmdir documentation page :
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
Sure it will make your life easier.
I know that this is a late answer, but I solved it by checking if the file exists or not.
I'm using database for the path of the file. So you may try an example code below.
if(!empty($course->picture)){
// unlink here
}
I have some problem with making a script move picture/files from one folder to another.
I put the code belw
Can somebody help me to see what im doing wrong?
Grateful for any tip that i'll have.
<?PHP
chdir( dirname( __FILE__ ) );
include '../../bootstrap.php';
config( 'website.config' );
config( 'website.countries' );
import( 'system.cli' );
class adeleflytte extends Script {
Public function Main(){
// Get array of all source files
$files = scandir("pictures");
// Identify directories
$source = "pictures";
$destination = "/movedpictures";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
}
}
CLI::Execute();
?>
rename function does this
rename
rename('image1.jpg', 'del/image1.jpg');
I think that the best way to move a file is to use a native function:
http://www.php.net/rename
As a parameters it accepts also full path, so it does move files as you need it.
Outputting what you're trying to copy is useful and would help track down the issue:
copy($source.$file, $destination.$file)
In this case since source is 'pictures' and $file is, say, 'pic.jpg' you are trying to copy
picturespic.jpg
You need to add / between these.
Additionally your destination /movedpictures is in the root directory of the filesystem which is likely not what you intended.
Im trying to Delete ALL Text files from a directory using a php script.
Here is what I have tried.....
<?php array_map('unlink', glob("/paste/*.txt")); ?>
I dont get an Error when I run this, yet It doesnt do the job.
Is there a snippet for this? Im not sure what else to try.
Your Implementation works all you need to do is use Use full PATH
Example
$fullPath = __DIR__ . "/test/" ;
array_map('unlink', glob( "$fullPath*.log"))
I expanded the submitted answers a little bit so that you can flexibly and recursively unlink text files located underneath as it's often the case.
// #param string Target directory
// #param string Target file extension
// #return boolean True on success, False on failure
function unlink_recursive($dir_name, $ext) {
// Exit if there's no such directory
if (!file_exists($dir_name)) {
return false;
}
// Open the target directory
$dir_handle = dir($dir_name);
// Take entries in the directory one at a time
while (false !== ($entry = $dir_handle->read())) {
if ($entry == '.' || $entry == '..') {
continue;
}
$abs_name = "$dir_name/$entry";
if (is_file($abs_name) && preg_match("/^.+\.$ext$/", $entry)) {
if (unlink($abs_name)) {
continue;
}
return false;
}
// Recurse on the children if the current entry happens to be a "directory"
if (is_dir($abs_name) || is_link($abs_name)) {
unlink_recursive($abs_name, $ext);
}
}
$dir_handle->close();
return true;
}
You could modify the method below but be careful. Make sure you have permissions to delete files. If all else fails, send an exec command and let linux do it
static function getFiles($directory) {
$looper = new RecursiveDirectoryIterator($directory);
foreach (new RecursiveIteratorIterator($looper) as $filename => $cur) {
$ext = trim($cur->getExtension());
if($ext=="txt"){
// remove file:
}
}
return $out;
}
i have modified submitted answers and made my own version,
in which i have made function which will iterate recursively in current directory and its all child level directories,
and it will unlink all the files with extension of .txt or whatever .[extension] you want to remove from all the directories, sub-directories and its all child level directories.
i have used :
glob() From the php doc:
The glob() function searches for all the pathnames matching pattern
according to the rules used by the libc glob() function, which is
similar to the rules used by common shells.
i have used GLOB_ONLYDIR flag because it will iterate through only directories, so it will be easier to get only directories and unlink the desired files from that directory.
<?php
//extension of files you want to remove.
$remove_ext = 'txt';
//remove desired extension files in current directory
array_map('unlink', glob("./*.$remove_ext"));
// below function will remove desired extensions files from all the directories recursively.
function removeRecursive($directory, $ext) {
array_map('unlink', glob("$directory/*.$ext"));
foreach (glob("$directory/*",GLOB_ONLYDIR) as $dir) {
removeRecursive($dir, $ext);
}
return true;
}
//traverse through all the directories in current directory
foreach (glob('./*',GLOB_ONLYDIR) as $dir) {
removeRecursive($dir, $remove_ext);
}
?>
For anyone who wonder how to delete (for example: All PDF files under public directory) you can do this:
array_map('unlink', glob( public_path('*.pdf')));
Trying to add the ability to delete a Folder using FTP and all subfolders and files contained within that folder.
I have built a recursive function to do so, and I feel like the logic is right, but still doesnt work.
I did some testing, I am able to delete on first run if the path is just an empty folder or just a file, but can't delete if it is a folder containing one file or a folder containing one empty subfolder. So it seems to be a problem with traversing through the folder(s) and using the function to delete.
Any ideas?
function ftpDelete($directory)
{
if(empty($directory))//Validate that a directory was sent, otherwise will delete ALL files/folders
return json_encode(false);
else{
global $conn_id;
# here we attempt to delete the file/directory
if( !(#ftp_rmdir($conn_id,$directory) || #ftp_delete($conn_id,$directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = #ftp_nlist($conn_id, $directory);
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file)
ftpDelete($file);
#if the file list is empty, delete the DIRECTORY we passed
ftpDelete($directory);
}
else
return json_encode(true);
}
};
I took some time to write my own version of a recursive delete function over ftp, this one should be fully functional (I tested it myself).
Try it out and modify it to fit your needs, if it's still not working there are other problems. Have you checked the permissions on the files you are trying to delete?
function ftp_rdel ($handle, $path) {
if (#ftp_delete ($handle, $path) === false) {
if ($children = #ftp_nlist ($handle, $path)) {
foreach ($children as $p)
ftp_rdel ($handle, $p);
}
#ftp_rmdir ($handle, $path);
}
}
Ok found my problem. Since I wasn't moving into the exact directory I was trying to delete, the path for each recursive file being called wasn't absolute:
function ftpDeleteDirectory($directory)
{
global $conn_id;
if(empty($directory))//Validate that a directory was sent, otherwise will delete ALL files/folders
return json_encode(false);
else{
# here we attempt to delete the file/directory
if( !(#ftp_rmdir($conn_id,$directory) || #ftp_delete($conn_id,$directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = #ftp_nlist($conn_id, $directory);
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file)
{
// return json_encode($filelist);
ftpDeleteDirectory($directory.'/'.$file);/***THIS IS WHERE I MUST RESEND ABSOLUTE PATH TO FILE***/
}
#if the file list is empty, delete the DIRECTORY we passed
ftpDeleteDirectory($directory);
}
}
return json_encode(true);
};
function recursiveDelete($handle, $directory)
{ echo $handle;
# here we attempt to delete the file/directory
if( !(#ftp_rmdir($handle, $directory) || #ftp_delete($handle, $directory)) )
{
# if the attempt to delete fails, get the file listing
$filelist = #ftp_nlist($handle, $directory);
// var_dump($filelist);exit;
# loop through the file list and recursively delete the FILE in the list
foreach($filelist as $file) {
recursiveDelete($handle, $file);
}
recursiveDelete($handle, $directory);
}
}
You have to check (using ftp_chdir) for every "file" you get from ftp_nlist to check if it is a directory:
foreach($filelist as $file)
{
$inDir = #ftp_chdir($conn_id, $file);
ftpDelete($file)
if ($inDir) #ftp_cdup($conn_id);
}
This easy trick will work, because if ftp_chdir works, the current $file is actually a folder, and you've moved into it. Then you call ftpDelete recursively, to let it delete the files in that folder. Afterwards, you move back (ftp_cdup) to continue.