deleting all files from a folder on Linux server using PHP - php

My question is almost the same as this one Deleting all files from a folder using PHP?
And I tried to use the answer provided by #Floern https://stackoverflow.com/a/4594262/2167772
But it didn't work for me. I tried to get filenames from a folder on the Linux server. And I have changed the folder and file permission to rwxrwxrwx. And I got the "Unable to get the filename" message all the time. Does anyone know how to solve it? Thanks a lot!
$files=glob('/data/in/*') or die ("Unable to get the filename");
foreach ($files as $file) {
if(is_file($file)){
echo $file;
unlink($file) or die ("Uable to delete file!");
}
}
------Update----
I just figured it out. It is the problem with the server. I cannot write anything to the data folder even I assign the write permission. I will move my in folder to another folder.
Thank you so much for everyone's comments!

As said #Marc B, you just have to write this :
$files=glob('data/in/*') or die ("Unable to get the filenames!");
foreach ($files as $file) {
if(is_file($file)){
echo $file;
unlink($file) or die ("Unable to delete file!");
}
}
You write : glob('/data/in/*'), I write glob('data/in/*')
You use absolute path, i use relative path.

Use this tutorial:
http://de3.php.net/manual/de/function.rmdir.php#107233
And check is your folder permission is enable to write.
Have you trying like this:
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}

if file is not at public directory...
change mode of file to 777
$files=glob('data/in/*') or die ("Unable to get the filename");
foreach ($files as $file) {
if(is_file($file)){
echo $file;
chmod($file,777);
unlink($file) or die ("Uable to delete file!");
}
}

solution with php. don't like the glob function. you can use the RecursiveDirectoryIterator
$filePath = '/someDir';
$directoryIterator = new \RecursiveDirectoryIterator(realpath($filePath));
foreach (new \RecursiveIteratorIterator($directoryIterator) as $object ) {
if(!$object->isDir())
{
unlink($object->getPath());
}
}

Related

delete_dir() from Codeigniter doesn't work

I get this error message when I try to delete a directory:
"Unable to delete the file" using PHP Codeigniter's delete_dir('/path/to/my/dir/'). No additional info provided.
There is no problem with the ftp conn (works with everything else), no problem with the file permission (delete_file() works jsut fine)..no problem with the code, the path is also valid. I'm all out of ideas and open for suggestions.
You can use unlink() to remove php directory.
function removedir($dir1) {
if (is_dir($dir1)) {
//scan
$files = scandir($dir1);
//loop through all the files
foreach ($files as $file) {
if ($file != "." && $file != "..") {
if (filetype($dir1."/".$file) == "dir1")
rrmdir($dir1."/".$file);
else
unlink($dir1."/".$file);
}
}
reset($files);
rmdir($dir);
}
}

failed to open stream: No such file or directory

Can anyone help with this one? I am new to web developing and not sure what this error means?
Warning: fopen(images/nophoto.png): failed to open stream: No such
file or directory in /home/u835626360/public_html/remove.html on line
101
can't this file/picture is open you need close
CODE:
$expire=time()-3600;
setcookie("dname","a", $expire);
setcookie("dpode","a", $expire);
}
function delpics($filename)
{
$path_to_file='userpics/';
$old = getcwd(); // Save the current directory
chdir($path_to_file);
$fh = fopen($filename, 'w') or die("can't this file/picture is open you need close ");
fclose($fh);
if (!unlink($filename))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $filename");
}
chdir($old); // Restore the old working directory
}
You need to give fopen the full path of the file, and you don't need chdir() at all. Try this version:
$path_to_file='userpics/';
$fh = fopen($path_to_file.$filename, 'w') or die('Permission error');
I was facing same problem. I was thinking file will be created if I use w or w+ but giving me above error.
So problem was we need to create dir before we can create file.
We can get absolute DIR path of file
$dir = dirname($filename);
Create DIR
//if(!is_dir($dir))
mkdir( $dir , 0755, true);
Third parameter is important you want recursively
I know it sound stupid but it may save someone's time so added here
First make the dir manually in your server(if you have one) or local pc(if you dev in local)
Be sure to have write right for apache in your dir (0777 in unix-linux if you wan't to be sure you can do what you wan't and no idea for windows)
and then like it was said give the good path to fopen and not only filename
Try this:
$expire=time()-3600;
setcookie("dname","a", $expire);
setcookie("dpode","a", $expire);
function delpics($filename)
{
$path_to_file='/userpics/';
$old = getcwd(); // Save the current directory
chdir($old.$path_to_file);
$fh = fopen($filename, 'w') or die("can't this file/picture is open you need close ");
fclose($fh);
if (!unlink($filename))
{
echo ("Error deleting $file");
}
else
{
echo ("Deleted $filename");
}
chdir($old); // Restore the old working directory
}

Create diectory (ftp_mkdir) only if files exist

I currently have a program that connects to an ftp directory, if it finds csv files, runs a script, then after the script has run on the files, it creates a back up folder with the date and moves the csv files to this newly created back up folder in the ftp directory.
However, if there are no csv files in the root directory, I do not want a backup folder to be created, as there are no files to move. I know the solution is probably really simple but I cannot seem to figure it out!
logMessage("Creating backups");
$ftp_connection = #ftp_connect($ftp_url, $ftp_port, 6000);
if(!#ftp_login($ftp_connection, $ftp_username, $ftp_password )) {
logMessage("Could not connect to FTP: [$ftp_url], with Username: [$ftp_username], and Password: [$ftp_password]");
die();
}
$date = date('Y_m_d_(His)');
$newBackup = $ftp_root."/".$ftp_backup."backup_$date";
if (ftp_mkdir($ftp_connection, $newBackup)) {
logMessage ("Successfully created [$newBackup\n]");
foreach($filesToProcess as $file){
$pathData = pathinfo($file);
if(isset($pathData['extension']) && $pathData['extension'] == 'csv'){
if(!#ftp_rename($ftp_connection,
$ftp_root.'/'.$file,
$newBackup."/".$file)
){
logMessage("Unable to move file: $file")
}
}
}
}
You have used, foreach($filesToProcess as $file) ,so in $filesToProcess it's array of files. you can use, count($filesToProcess) first count number of files, then if count>0 execute code.
// $csv = your checks for string ending to .csv
$ftp_files = ftp_nlist($ftp_connection, ".");
foreach ($ftp_files = $files) {
if ($files = $csv) {
// makedir
maybe something like this in very basic syntax. ftp_nlist returns an array of all files in a particular directory.

PHP - Deleting folder/files only if there are no more in there

$value can = a folder structure to the language file. Example: languages/english.php
$value can also = the files name. Example: english.php
So I need to get the current folder that $value is in and delete the folder ONLY if there are no other files/folders within that directory (after deleting the actual file as I am doing already, ofcourse).
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
#unlink($module_path . '/' . $value);
// Now I need to delete the folder ONLY if there are no other directories inside the folder where it is currently at.
// And ONLY if there are NO OTHER files within that folder also.
}
}
How can I do this?? And wondering if this can be done without using a while loop, since a while loop within a foreach loop could take some time, and need this to be as quick as possible.
And just FYI, the $module_path should never be deleted. So if $value = english.php, it should never delete the $module_path. Ofcourse, there will always be another file in there, so checking for this is not necessary, but won't hurt either way.
Thanks guys :)
EDIT
Ok, now I'm using this code here and it is NOT working, it is not removing the folders or the files, and I don't get any errors either... so not sure what the problem is here:
foreach($module['languages'] as $lang => $langFile)
{
foreach ($langFile as $type => $value)
{
if (#unlink($module_path . '/' . $value))
#rmdir(dirname($module_path . '/' . $value));
}
}
NEVERMIND, this works a CHARM!!! Cheers Everyone!!
The easyest way is try to use rmdir. This don't delete folder if it is not empty
rmdir($module_path);
also you can check is folder empty by
if(count(glob($module_path.'*'))<3)//delete
2 for . and ..
UPD: as I reviewed maybe you should replace $module_path by dirname($module_path.'.'.$value);
Since the directory you care about might be part of the $value, you need to use dirname to figure out what the parent directory is, you can't just assume that it's $module_path.
$file_path = $module_path . '/' . $value;
if (#unlink($file_path)) {
#rmdir(dirname($file_path));
}
if (is_file($value)) {
unlink($value);
} else if (is_dir($value)) {
if (count(scandir($value)) == 2) }
unlink($value)
}
}
http://php.net/manual/en/function.is-dir.php
http://www.php.net/manual/en/function.scandir.php
The code below will take a path, check if it is a file (i.e. not a directory). If it is a file, it will extract the directory name, then delete the file, then iterate over the dir and count the files in it, if the files are zero it'll delete the dir.
Code is as an example and should work, however privileges and environment setup may result in it not working.
<?php
if(!is_dir ( string $filename )){ //if it is a file
$fileDir = dirname ( $filename );
if ($handle = opendir($fileDir)) {
echo "Directory handle: $handle\n";
echo "Files:\n";
$numFiles=0;
//delete the file
unlink($myFile);
//Loop the dir and count the file in it
while (false !== ($file = readdir($handle))) {
$numFiles = $numFiles + 1;
}
if($numFiles == 0) {
//delete the dir
rmdir($fileDir);
}
closedir($handle);
}
}
?>

I need to find a file in directory and copy it to a different directory

I merely have the file name, without extension (.txt, .eps, etc.)
The directory has several subfolders. So, the file could be anywhere.
How can I seek the filename, without the extension, and copy it to different directory?
http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt seems to be exactly what you need, to find the file. then just use the normal php copy() command http://php.net/manual/en/function.copy.php to copy it.
https://stackoverflow.com/search?q=php+recursive+file
have a look at this http://php.net/manual/en/function.copy.php
as for seeking filenames, could use a database to log where the files are? and use that log to find your files
I found that scandir() is the fastest method for such operations:
function findRecursive($folder, $file) {
foreach (scandir($folder) as $filename) {
$path = $folder . '/' . $filename;
# $filename starts with desired string
if (strpos($filename, $file) === 0) {
return $path;
}
# search sub-directories
if (is_dir($path)) {
$result = findRecursive($path);
if ($result !== NULL) {
return $result;
}
}
}
}
For copying the file, you can use copy():
copy(findRecursive($folder, $partOfFilename), $targetFile);

Categories