php unable to delete Images - php

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 is working fine and it delete story images but delete post does not delete images.

Related

File name too long while deleting image in Laravel

I am working on a Laravel project, the code saves the image inside a folder created with the title coming from a post. The problem is that while adding post it does not gives a warning saying filename too long but while deleting the post it says filename too long in demo.php/uploads/filename.php.
Is it really because of long folder name or something else?
The following code is called for deleting the folder while deleting a post.
function rmdir_recursive($dir) {
if (is_array($dir) || is_object($dir))
{
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
}
if (is_string($dir)) {
rmdir($dir);
}
}
Following the function to add post:
function create()
{
if($_SERVER['REQUEST_METHOD']=="POST")
{
$pid = rand(1000,9000);
$title = $_POST['title'];
$descpt = $_POST['description'];
$push = isset($_POST['send_push']) ? $_POST['send_push'] : "";
$feature_image = array();
$fy = $_POST['fy'];
if(empty($title) || empty($descpt) || empty($fy))
{
array_push($this->errors, MEND_FIELD_ERROR);
return;
}
if(!empty($_FILES['feature_image']['name'][0]))
{
$image = $_FILES['feature_image'];
$allowed_ext = array('jpeg','jpg','png','pdf','docx');
$allowed_size = 20000000;
foreach($image['name'] as $pos=>$image_name)
{
$dir = "./cdn/uploads/notice/".$title;
$tmp = $image['tmp_name'][$pos];
$img_size = $image['size'][$pos];
$img_error = $image['error'][$pos];
$img_ext = explode('.', $image_name);
$img_name = $img_ext[0];
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed_ext))
{
if($img_size <= $allowed_size)
{
if(!file_exists($dir))
{
mkdir($dir);
}
$image_new_name = $img_name.'$$'.uniqid('', true).'.'.$img_ext;
$upload_destination = $dir.'/'.$image_new_name;
if(move_uploaded_file($tmp, $upload_destination))
{
array_push($feature_image, $image_new_name);
}
else
{
array_push($this->errors, $img_error);
return;
}
}
}
else
{
array_push($this->errors, $img_ext.' is not an allowed file extension.');
return;
}
}
}
$s_feature_image = json_encode($feature_image, JSON_UNESCAPED_UNICODE);
$statement = $this->db->prepare("INSERT INTO `notice` (`pid`,`title`,`descpt`,`date`,`photo`,`fy`)
VALUES (?,?,?,?,?,?)");
if($statement->execute([$pid,$title,$descpt,DAT, $s_feature_image, $fy]))
{
if($push == "checked")
{
$descpt = strip_tags($descpt);
$tek = array("message"=>$descpt,"title"=>$title);
$tokens = $this->getTokens();
$this->push_notification($tokens,$tek);
}
ExitThis::send_to(URL.'notice?id='.$pid);
}
else
{
array_push($this->errors, DATABASE_ERROR);
return;
}
}
}
Note: The title will be Nepali character.
I don't know this was right but deleting folder if that is not string help me. I did following changes in my code:
function rmdir_recursive($dir) {
if (is_array($dir) || is_object($dir))
{
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
}
if(!is_string($dir)){
rmdir($dir);
}
}

PHP Directory, subdirectory and file Listing default sort order

i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);

Remove all files, folders and their subfolders with php [duplicate]

This question already has answers here:
Delete directory with files in it?
(34 answers)
Closed 5 years ago.
I need a script which can remove a whole directory with all their subfolders, files and etc. I tried with this function which I found in internet before few months ago but it not work completely.
function deleteFile($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(!deleteFile($dir.$obj)) {
echo $dir.$obj."<br />";
return false;
}
}
elseif(is_file($dir.$obj)) {
if(!unlink($dir.$obj)) {
echo $dir.$obj."<br />";
return false;
}
}
}
}
closedir($handle);
if(!#rmdir($dir)) {
echo $dir.'<br />';
return false;
}
return true;
}
return true;
}
For the test I use a unpacked archive of prestashop and I try to delete the folder where archive is unpacked but it doesn't work.
/home/***/public_html/prestashop/img/p/3/
/home/***/public_html/prestashop/img/p/3
/home/***/public_html/prestashop/img/p
/home/***/public_html/prestashop/img
These are the problem folders. At the first time I think - "May is a problem with the chmod of the files" but when I test with all files chmod permission 755 (after that with 777) - the result was the same.
<?php
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);
}
}
?>
Try out the above code from php.net
Worked fine for me
function delete_files($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) delete_files($file); else unlink($file);
} rmdir($dir);
}
You can use a cleaner method for doing a recursive delete of a directory.
Example:
function recursiveRemove($dir) {
$structure = glob(rtrim($dir, "/").'/*');
if (is_array($structure)) {
foreach($structure as $file) {
if (is_dir($file)) recursiveRemove($file);
elseif (is_file($file)) unlink($file);
}
}
rmdir($dir);
}
Usage:
recursiveRemove("test/dir/");
The easiest and the best way using the system() method
$dir = dirname ( "/log" );
if ($handle = opendir($dir)) {
while (( $file = readdir($handle)) !== false ) {
if ($file != "." && $file != "..") {
system("rm -rf ".escapeshellarg($dir.'/'.$file));
}
}
}
closedir($handle);
/**
* Deletes a directory and all files and folders under it
* #return Null
* #param $dir String Directory Path
*/
function rmdir_files($dir) {
$dh = opendir($dir);
if ($dh) {
while($file = readdir($dh)) {
if (!in_array($file, array('.', '..'))) {
if (is_file($dir.$file)) {
unlink($dir.$file);
}
else if (is_dir($dir.$file)) {
rmdir_files($dir.$file);
}
}
}
rmdir($dir);
}
}

PHP Deleting a full folder

I have the following function that I am trying to use to delete a full folder but it does not seem to be deleting any ideas or recommendations?
public function submit()
{
$location = $_SERVER['DOCUMENT_ROOT'].'/_assets/quote/uploads/';
$folderName = $this->quote->getCompanyDetails()->companyName;
$data['companyContact'] = $this->quote->getCompanyDetails()->companyContact;
$this->load->view('submit',$data);
$this->quote->removeQuote();
if(is_dir($location.$folderName) === TRUE)
{
$files = array_diff(scandir($location.$folderName), array('.','..'));
foreach($files as $file)
{
Delete(realpath($location.$folderName).'/'. $file);
}
return rmdir($location.$folderName);
}
else if(is_file($location.$folderName) === TRUE)
{
return unlink($location.$folderName);
}
return FALSE;
}
Update:
public function submit()
{
$location = $_SERVER['DOCUMENT_ROOT'].'/_assets/quote/uploads/';
$folderName = $this->quote->getCompanyDetails()->companyName;
$data['companyContact'] = $this->quote->getCompanyDetails()->companyContact;
$this->load->view('submit',$data);
//$this->quote->removeQuote();
$this->removeFolder();
}
private function removeFolder(){
$location = $_SERVER['DOCUMENT_ROOT'].'/_assets/quote/uploads/';
$folderName = $this->quote->getCompanyDetails()->companyName;
foreach(glob($location.$folderName.'/*') as $file)
{
if(is_dir($location.$folderName))
{
rmdir($location.$folderName);
}else{
unlink($location.$folderName);
}
rmdir($location.$folderName);
}
}
You cannot delete a full folder in one call. You should do it recursively:
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
}
rmdir($dir);
}

building a simple directory browser using php RecursiveDirectoryIterator

Hi
i am trying to build simple directory browser to browse folders and sub-folders uing php RecursiveDirectoryIterator .. i need help of how to create this. i have started with the following code.
$dir = dirname(__FILE__); //path of the directory to read
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if (!$file->isFile()) { //create hyperlink if this is a folder
echo "" . $file->getFilename() . "\";
}else{ //do not link if this is a file
$file->getFilename()
}
}
Allow me to code that for you....
<?php
$root = __DIR__;
function is_in_dir($file, $directory, $recursive = true, $limit = 1000) {
$directory = realpath($directory);
$parent = realpath($file);
$i = 0;
while ($parent) {
if ($directory == $parent) return true;
if ($parent == dirname($parent) || !$recursive) break;
$parent = dirname($parent);
}
return false;
}
$path = null;
if (isset($_GET['file'])) {
$path = $_GET['file'];
if (!is_in_dir($_GET['file'], $root)) {
$path = null;
} else {
$path = '/'.$path;
}
}
if (is_file($root.$path)) {
readfile($root.$path);
return;
}
if ($path) echo '..<br />';
foreach (glob($root.$path.'/*') as $file) {
$file = realpath($file);
$link = substr($file, strlen($root) + 1);
echo ''.basename($file).'<br />';
}

Categories