Deleting a file from storage does not delete an image - php

I'm using Laravel 5.8 and I wanted to delete an image from storage directory.
Basically the images is placed at this dir:
/storage/app/public/laboratories/labs/21/pics
And I tried running this method:
public function removeAzPic($lab,$azpic)
{
$destinationPath = storage_path("laboratories/labs/$lab/pics/$azpic");
Storage::delete($destinationPath);
return redirect()->back();
}
But the problem is it does not delete the file from storage!
So what's going wrong here? How can I solve this issue?

You can add this function to the helper.php for to delete files/directories recursively:
Function will help you to delete files at the moment. If you want to delete directories change if ( is_dir($full) ) { to if ( is_file($full) ) {
public static function rrmdir($src = null) {
if(!is_dir($src)) return false;
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
$full = $src . '/' . $file;
if ( is_dir($full) ) {
self::rrmdir($full);
} else {
#unlink($full);
}
}
}
closedir($dir);
rmdir($src);
return true;
}

Related

Delete post file not working in php function

I have below code to delete posts from my website. This function is working for video posts and it delete video post perfectly. But it is not working for image posts and does not delete post image from web directory. My code is
function delete_post($id, $fromStory = false) {
$post = get_post($id);
if ($fromStory and !$post['is_story']) return true;
if (!$fromStory and !can_edit_post($post)) return false;
if ($post['images']) {
$images = perfectUnserialize($post['images']);
if($images) {
foreach($images as $image) {
delete_file(path($image));
}
}
if ($post['video']) {
delete_file(path($post['video']));
}
}
Besides i have delete old stories function given below
function delete_old_stories() {
$time = time() - (3600 * config('story-deleted-at', 24));
$query = db()->query("SELECT id,post_id FROM story_posts WHERE time_created < $time ");
while($fetch = $query->fetch(PDO::FETCH_ASSOC)) {
db()->query("DELETE FROM story_posts WHERE id=?", $fetch['id']); //delete story posts
delete_post($fetch['post_id'], true);
}
return true;
}
This is delete file function
function delete_file($path)
{
$basePath = path();
$basePath2 = $basePath . '/';
if ($path == $basePath or $path == $basePath2) return false;
if (is_dir($path) === true) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if (in_array($file->getBasename(), array('.', '..')) !== true) {
if ($file->isDir() === true) {
rmdir($file->getPathName());
} else if (($file->isFile() === true) || ($file->isLink() === true)) {
unlink($file->getPathname());
}
}
}
return rmdir($path);
} else if ((is_file($path) === true) || (is_link($path) === true)) {
return unlink($path);
}
return false;
}
For each story,
Image file in directory is
_1000_8f81946314be5cfe962480b96c7df11e.jpg
For Post,
Image files in directory are
_1000_8f81946314be5cfe962480b96c7df11e.jpg
_600_8f81946314be5cfe962480b96c7df11e.jpg
Delete Story working fine and deletes story images but delete post does not delete images.
i have tried var_dump it is giving message as string(94)
"/home3/myaim/abc.com/files/uploads/posts/photo/_%w_79b3d75a626fc66d67eee4ec9289‌​bd0a.jpg" Post deleted successfully
but image file path which is to be deleted is string(94)
"/home3/myaim/abc.com/files/uploads/posts/photo/_1000_79b3d75a626fc66d67eee4ec92‌​89bd0a.jpg" Post deleted successfully
Any suggestion?
you can use unlink for Delete a filename.
example:
unlink('imageText.jpg');

Codeigniter delete the directory and its contents

I am trying to make codeigniter delete a product image folder.
Furthermore, the delete function I am trying to make needs to delete also all of its contents, so empty or not, the folder gets deleted. I'm guessing, it would use a recursive type of deletion...I'm not so sure at all.
I have tried the below functions for deleting :
function delete_directory($path)
{
$path=base_url().'products/thumb/';
$this->load->helper("file"); // load the helper
delete_files($path, true); // delete all files/folders
//rmdir($dirname);
if(rmdir($path)){
echo 'deleted';die;}
else{
echo 'not';die; }
return true;
}
But it always returning not
Deleting directory content:
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]);
}
create an helper. see below:-
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('remove_directory'))
{
function remove_directory($directory, $empty=FALSE)
{
if(substr($directory,-1) == '/') {
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory)) {
return FALSE;
} elseif(!is_readable($directory)) {
return FALSE;
} else {
$handle = opendir($directory);
while (FALSE !== ($item = readdir($handle)))
{
if($item != '.' && $item != '..') {
$path = $directory.'/'.$item;
if(is_dir($path)) {
remove_directory($path);
}else{
unlink($path);
}
}
}
closedir($handle);
if($empty == FALSE)
{
if(!rmdir($directory))
{
return FALSE;
}
}
return TRUE;
}
}
}
then load this helper in Your controller and call function remove_directory()
/* End of file recursive_helper.php */
/* Location: /application/helpers/recursive_helper.php */
Delete all files:
delete_files('./path/to/your/directory/');
Include sub-folder(s):
delete_files('./path/to/your/directory/', TRUE);

PHP recursive delete function

I wrote recursive PHP function for folder deletion. I wonder, how do I modify this function to delete all files and folders in webhosting, excluding given array of files and folder names (for ex. cgi-bin, .htaccess)?
BTW
to use this function to totally remove a directory calling like this
recursive_remove_directory('path/to/directory/to/delete');
to use this function to empty a directory calling like this:
recursive_remove_directory('path/to/full_directory',TRUE);
Now the function is
function recursive_remove_directory($directory, $empty=FALSE)
{
// if the path has a slash at the end we remove it here
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
// if the path is not valid or is not a directory ...
if(!file_exists($directory) || !is_dir($directory))
{
// ... we return false and exit the function
return FALSE;
// ... if the path is not readable
}elseif(!is_readable($directory))
{
// ... we return false and exit the function
return FALSE;
// ... else if the path is readable
}else{
// we open the directory
$handle = opendir($directory);
// and scan through the items inside
while (FALSE !== ($item = readdir($handle)))
{
// if the filepointer is not the current directory
// or the parent directory
if($item != '.' && $item != '..')
{
// we build the new path to delete
$path = $directory.'/'.$item;
// if the new path is a directory
if(is_dir($path))
{
// we call this function with the new path
recursive_remove_directory($path);
// if the new path is a file
}else{
// we remove the file
unlink($path);
}
}
}
// close the directory
closedir($handle);
// if the option to empty is not set to true
if($empty == FALSE)
{
// try to delete the now empty directory
if(!rmdir($directory))
{
// return false if not possible
return FALSE;
}
}
// return success
return TRUE;
}
}
Try something like this:
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('%yourBaseDir%'),
RecursiveIteratorIterator::CHILD_FIRST
);
$excludeDirsNames = array();
$excludeFileNames = array('.htaccess');
foreach($it as $entry) {
if ($entry->isDir()) {
if (!in_array($entry->getBasename(), $excludeDirsNames)) {
try {
rmdir($entry->getPathname());
}
catch (Exception $ex) {
// dir not empty
}
}
}
elseif (!in_array($entry->getFileName(), $excludeFileNames)) {
unlink($entry->getPathname());
}
}
I'm using this function to delete the folder with all files and subfolders:
function removedir($dir) {
if (substr($dir, strlen($dir) - 1, 1) != '/')
$dir .= '/';
if ($handle = opendir($dir)) {
while ($obj = readdir($handle)) {
if ($obj != '.' && $obj != '..') {
if (is_dir($dir . $obj)) {
if (!removedir($dir . $obj))
return false;
}
else if (is_file($dir . $obj)) {
if (!unlink($dir . $obj))
return false;
}
}
}
closedir($handle);
if (!#rmdir($dir))
return false;
return true;
}
return false;
}
$folder_to_delete = "folder"; // folder to be deleted
echo removedir($folder_to_delete) ? 'done' : 'not done';
Iirc I got this from php.net
You could provide an extra array parameter $exclusions to recursive_remove_directory(), but you'll have to pass this parameter every time recursively.
Make $exclusions global. This way it can be accessed in every level of recursion.

Check if folder is empty outputs error (PHP)

I have a code to check if directory is empty, so that i will be able to perform actions, but this simple code gives an error:
Warning: opendir(/Site/images/countries/abc/a/2.swf,/Site/images/countries/abc/a/2.swf) [function.opendir]: The system cannot find the path specified. (code: 3) in C:\wamp\www\Site\index.PHP on line 374
There is no such file
function IsNotEmpty($folder){
$files = array ();
if ( $handle = opendir ( $folder ) )
{
while ( false !== ( $file = readdir ( $handle ) ) )
{
if ( $file != "." && $file != ".." )
{
$files [] = $file;
}
}
closedir ( $handle );
}
return ( count ( $files ) > 0 ) ? TRUE: FALSE; }
$dir ="/Site/images/countries/abc/a/2.swf";
if (IsNotEmpty($dir)==true)
{
echo "There is no such file";
}
else
{
echo "The file exists!";
};
I don't understand what is wrong here. The file exits in the specified directory.
opendir is for opening directories, not files :-)
You can also try temporarily putting in debug stuff so that you can see what's happening:
function IsNotEmpty ($folder) {
$files = array ();
if ($handle = opendir ($folder)) {
echo "DEBUG opened okay ";
while (false !== ($file = readdir ($handle))) {
if ( $file != "." && $file != ".." ) {
$files [] = $file;
echo "DEBUG got a file ";
}
}
closedir ($handle);
} else {
echo "DEBUG cannot open ";
}
return (count($files) > 0 ) ? TRUE : FALSE;
}
$dir ="/Site/images/countries/abc/a";
if (IsNotEmpty($dir)) {
echo "There is no such file";
} else {
echo "The file exists!";
}
If that's still not working and you're sure the directory exists (remember, case is important for UNIX), you may want to look into the permissions on that directory to ensure that the user ID trying to access it is allowed.
You chould use the following snippet as body for your function:
$aFiles = glob($sFolder);
return (sizeof($aFiles) < 1) true : false;
This will get the contents of the folder as an array, when empty - your directory is empty.
Try for instance this:
function IsNotEmpty($dir) {
$dir = rtrim($dir, '/').'/';
return is_dir($dir) && count(glob($dir.'*.*') > 2);
}
Christine, try removing the trailing slash:
$dir ="/Site/images/countries/abc/a/"
Becomes
$dir ="/Site/images/countries/abc/a"

Delete folder in php

I am trying to delete a folder using this script :
function Delete($path)
{
if (is_dir($path) === true)
{
$files = array_diff(scandir($path), array('.', '..'));
foreach ($files as $file)
{
Delete(realpath($path) . '/' . $file);
}
return rmdir($path);
}
else if (is_file($path) === true)
{
return unlink($path);
}
return false;
}
Delete('tmp');
It works in my Xampp server, but not on my webserver. I have changed the permissions of the folder and of the file it contains to 0777. So it should be writable(or in this case erasable) but nothing happens. I have even tryied giving the absolute path of the folder as the parameter of the function, but still nothing.Any ideas?
Use this :
function delTree($dir)
{
$files = glob( $dir . '*', GLOB_MARK );
foreach( $files as $file
{
if( is_dir( $file ) )
delTree( $file );
else
#unlink( $file );
}
if( is_dir($dir) ) rmdir( $dir );
};
Does it return false? Or it returns true but doesn't actually remove?
Normally I'd just guess it's a permissions problem.
Try making a folder with mkdir from PHP so PHP is the owner (so to speak) and try to remove that with your function.
If it works, it's a permissions/owner issue.
You can Try this code
<?php
$files = glob('application/*'); foreach($files as $file){ if(is_file($file)) unlink($file); }
?>
Or,
function viewDir($path) {
return is_file($path) ?
#unlink($path) :
array_map(__FUNCTION__, glob($path.'/*')) == #rmdir($path);
}
$dir=$_SERVER["DOCUMENT_ROOT"]."/xxxx/xxxx";
echo $dir;
viewDir($dir);
May be some files are opened using php like fopen and that time it will not delete the folder or directory. I have faced the same issue when I tried to delete a file/folder
Try something like this.
<?php
function delete_directory($target) {
if (is_dir($target))
$dir_handle = opendir($target);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($target.'/'.$file);
}
}
closedir($dir_handle);
rmdir($target);
return true;
}
?>
Hope this helps.
Try this line of code to delete a folder or folder files
I hope this will help you
function deleteAll($str) {
if (is_file($str)) {
return unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
$this->deleteAll($path);
}
return #rmdir($str);
}
}

Categories