File name too long while deleting image in Laravel - php

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);
}
}

Related

php unable to delete Images

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.

move_uploaded_file() function doesn't save uploaded file on server

I've been working on a php script which creates a folder and saves posted images in the created folder, the folders get created but the images I aren't saved.
Below is the script:
if (isset($_FILES['images'])) {
mkdir("files/test/".$new."/", 0755, true);
foreach ($_FILES['images']['tmp_name'] as $key => $value) {
if (!(empty($_FILES['images']['tmp_name'][$key]) || $_FILES['images']['tmp_name'][$key] == 'none')) {
$i_slika = 1;
$extenzion = strtolower(end(explode(".", $_FILES['images']['name'][$key])));
$file = "files/nekretnina/".$new."/".$i_slika.".".$extenzion;
while (file_exists($file)) {
$i_slika++;
$file = "files/nekretnina/".$new."/".$i_slika.".".$extenzion;
}
if (!#move_uploaded_file($_FILES['images']['tmp_name'][$key], $file)) {
$err_text = $err_text. 'Error: '.$_FILES['images']['name'][$key].'<br />';
} else {
include_once "thumbz.class.php";
$pic = new thumbz($file);
$pic->dimensionImage("resize",640);
$pic->addParam('l',0);
$pic->render($file);
}
}
}
}
You need to use $_FILES['images']['tmp_name'][$key] instead of $_FILES['slika']['tmp_name'][$key].
You have the wrong index name!
Try Using:
if (isset($_FILES['images'])) {
mkdir("files/test/".$new."/", 0755, true);
foreach ($_FILES['images']['tmp_name'] as $key => $value) {
if (!(empty($_FILES['images']['tmp_name'][$key]) || $_FILES['images']['tmp_name'][$key] == 'none')) {
$i_slika = 1;
$extenzion = strtolower(end(explode(".", $_FILES['images']['name'][$key])));
$file = "files/test/".$new."/".$i_slika.".".$extenzion;
while (file_exists($file)) {
$i_slika++;
$file = "files/test/".$new."/".$i_slika.".".$extenzion;
}
if (!#move_uploaded_file($_FILES['images']['tmp_name'][$key], $file)) {
$err_text = $err_text. 'Error: '.$_FILES['images']['name'][$key].'<br />';
} else {
include_once "thumbz.class.php";
$pic = new thumbz($file);
$pic->dimensionImage("resize",640);
$pic->addParam('l',0);
$pic->render($file);
}
}
}
}

Auto Photo Albums in codeigniter

I have used Auto Photo Albums – Multi Level Image Grid for integration of my gallery in my website, it is easily integrated in core PHP but when am using codeigniter frame work for integration of this plugin am unable to get the images
The plugin consists of three files with a directory
reader.php
gallery.html
Reader.php
<?php
//CONFIGURATION
$imgTypes = array('jpeg', 'jpg', 'png', 'gif'); // The extensions of Images that the plugin will read
$imagesOrder = $_GET['imagesOrder']; //byDate, byDateReverse, byName, byNameReverse, random
$folderCoverRandom = $_GET['folderCoverRandom'];
$albumsOrder = $_GET['albumsOrder'];
function getList ($directory, $type='none') {
global $imgTypes;
global $imagesOrder;
global $albumsOrder;
$order = $imagesOrder;
if($type == 'albums'){
$order = $albumsOrder;
}
if( !is_dir($directory)){
return array();
}
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != ".." && $file != ".DS_Store" && $file != "#eaDir") {
$extension = preg_split('/\./',$file);
$extension = strtolower($extension[count($extension)-1]);
if($type == 'none'){
//do nothing
}else if($type == 'albums'){
if( !is_dir($directory.'/'.$file) ){
continue;
}
}else if($type == 'images'){
if( is_dir($directory.'/'.$file) ){
continue;
}
}
if( (array_search($extension,$imgTypes) !== FALSE || is_dir($directory.'/'.$file)) && $file != "thumbnails" ){
$ctime = filemtime($directory .'/'. $file) . ',' . $file; //BRING THE DATE OF THE IMAGE
if($order == 'byName' || $order == 'byNameReverse'){
$ctime = $file;
}
$results[$ctime] = $file;
}
}
}
closedir($handler);
if($order == 'byDate' || $order == 'byNameReverse'){
krsort($results);
}else if($order == 'byDateReverse' || $order == 'byName'){
ksort($results);
}else if($order == 'random'){
shuffle($results);
}
return $results;
}
function fixArray($list, $directory){
global $folderCoverRandom;
$return = array();
foreach ($list as $key => $value) {
$val = "";
if( is_dir($directory.'/'.$value) ){
$val = "folder";
$arr = getList($directory.'/'.$value);
$folderImg = "";
$folderImgCover = "";
$thumb = 'no';
$numImg = 0;
$numFolders = 0;
foreach ($arr as $key2 => $value2) {
if( is_dir( $directory.'/'.$value.'/'.$value2) ){//IF IT IS A FOLDER
$numFolders++;
}else{//IF IT IS AN IMAGE
//PICK THE FIRST IMAGES FROM THE FOLDER TO USE IT AS COVER IMAGE
if( $folderImg == "" ){
$folderImg = $value2;
if( file_exists( $directory.'/'.$value.'/thumbnails'.'/'.$value2 ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
}
//VERIFY IF THERE IS ANY "folderCover" IMAGE IN THE FOLDER SO WE CAN USE IT AS COVER IMAGE
$arrName = preg_split('/\.(?=[^.]*$)/',$value2);
$imgName = $arrName[0];
if( $folderImgCover == "" && $imgName == "folderCover" ){
$folderImgCover = $value2;
}
if($imgName != "folderCover"){
$numImg++;
}
}
}
//PICK A RANDOM IMAGES FROM THE FOLDER TO USE IT AS RANDOM IMAGE
if($folderCoverRandom == 'true'){
$rand = rand(0,$numImg-1);
$cont = 0;
foreach ($arr as $key2 => $value2) {
if( is_dir( $directory.'/'.$value.'/'.$value2) ){//IF IT IS A FOLDER
// DO NOTHING
}else{//IF IT IS AN IMAGE
if($cont == $rand){
$folderImg = $value2;
if( file_exists( $directory.'/'.$value.'/thumbnails'.'/'.$value2 ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
}
$cont++;
}
}
}
//IF THERE IS A COVER IMAGE INSIDE THE FOLDER THEN USE IT!
if( $folderImgCover != "" ){
$folderImg = $folderImgCover;
$thumb = "no";
}
$val = array('numImages' => $numImg, 'numFolders' => $numFolders, 'image' => $folderImg, 'thumb' => $thumb);
}else{
$thumb = 'no';
if( file_exists( $directory.'/thumbnails'.'/'.$value ) ){//VERIFY IF THERE IS ANY THUMBNAIL FOR THE IMAGE
$thumb = 'yes';
}
$val = $thumb;
}
$return[$value] = $val;
}
return $return;
}
$directory = $_GET['directory'];
//THE RESULT OF THE JSON CALL
$output = array();
$list = array();
if($albumsOrder != 'none'){//Apply a different order to the folders
$albums = getList($directory, 'albums');
$images = getList($directory, 'images');
$list = $albums + $images;
}else{
//GET LIST OF IMAGES AND FOLDERS
$list = getList($directory);
}
$output = fixArray($list, $directory);
// print_r($output);
//echo json_encode($output, JSON_FORCE_OBJECT); // if you are using PHP 5.3 plase use this line instead of the one below
echo json_encode($output);
?>
Gallery.html
<div class="container-fluid">
<div id="grid" data-directory="Gallery"></div>
</div>
All the images are loaded into the directory i,e Gallery Folder the images are retrieved into the page by using the reader file
When i have integrated the same files in codeigniter the are images are unable to load
I have created reader.php as a library and i have called it in the controller but it shows error
Undefined index: imagesOrder
Undefined index: folderCoverRandom
Undefined index: directory
Gallery Output :http://www.davidbo.dreamhosters.com/plugins/AutoAlbums/plugin/index2.html
Plugin : https://codecanyon.net/item/auto-photo-albums-multi-level-image-grid/5319229
Please help me out how can i integrate this to codeigniter

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);
}

How to delete all files under a specified directory with PHP?

I think the title is clear.
$dir = '/some/path/to/delete/';//note the trailing slashes
$dh = opendir($dir);
while($file = readdir($dh))
{
if(!is_dir($file))
{
#unlink($dir.$file);
}
}
closedir($dh);
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;
}
http://us.php.net/manual/en/function.unlink.php.
You will find many functions in the comments that does what you need
One example:
function unlinkRecursive($dir, $deleteRootToo)
{
if(!$dh = #opendir($dir))
{
return;
}
while (false !== ($obj = readdir($dh)))
{
if($obj == '.' || $obj == '..')
{
continue;
}
if (!#unlink($dir . '/' . $obj))
{
unlinkRecursive($dir.'/'.$obj, true);
}
}
closedir($dh);
if ($deleteRootToo)
{
#rmdir($dir);
}
return;
}
This function will remove recursively (like rm -r). Be careful!
function rm_recursive($filepath)
{
if (is_dir($filepath) && !is_link($filepath))
{
if ($dh = opendir($filepath))
{
while (($sf = readdir($dh)) !== false)
{
if ($sf == '.' || $sf == '..')
{
continue;
}
if (!rm_recursive($filepath.'/'.$sf))
{
throw new Exception($filepath.'/'.$sf.' could not be deleted.');
}
}
closedir($dh);
}
return rmdir($filepath);
}
return unlink($filepath);
}

Categories