Laravel 5 | File upload - If file exists add number to filename - laravel

I have problem with file upload. Now I have something like this (part of Controller):
if($request->has('photos')) {
foreach ($request->photos as $photo) {
$filename = $photo->getClientOriginalName();
$tmp_name = $filename;
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$uniq_no = 0;
while (file_exists($filename)) {
$tmp_name = $name .'_'. $uniq_no . $ext;
$uniq_no++;
}
$photo->storeAs('public/photos/',$tmp_name);
Photo::create([
'page_id' => $page->id,
'filename' => $tmp_name
]);
}
}
but saves to the database without adding a unique number: filename_0, filename_1 etc. It just saves the value of $tmp_name.
What am I doing wrong?

I did something like this:
if($request->has('photos')) {
foreach ($request->photos as $photo) {
$file = $photo->getClientOriginalName();
$filename = pathinfo($file, PATHINFO_FILENAME).'_'.Str::random(6);
$extension = pathinfo($file, PATHINFO_EXTENSION);
$fullfilename = $filename .'.'. $extension;
$photo->storeAs('public/photos/',$fullfilename);
Photo::create([
'page_id' => $page->id,
'filename' => $fullfilename
]);
}
}

Related

Laravel 8 can not upload .apk file

Laravel 8 cannot upload .apk files. I get the following error.
[error:Symfony\Component\HttpFoundation\File\UploadedFile:private] =>
1
if ($request->hasFile('file_name')) {
$filenameWithExt = $request->file('file_name')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('file_name')->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
$fileNameToStore = $filenameWithExt;
$path = $request->file('file_name')->storeAs('public/apkfile/', $fileNameToStore);
$apkstore = Apkfile::find($apk->id);
$apkstore->file_name = $fileNameToStore;
$apkstore->save();
}
}
if($request->file('file_name')){
$apk = Apkfile::create([
'apk_name' => $request->apk_name,
'package_name' => $request->package_name,
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
]);
$filenameWithExt = $request->file('file_name')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('file_name')->getClientOriginalExtension();
$check=in_array($extension,$allowedfileExtension);
if ($check) {
//$fileNameToStore = $filename. '.' . $extension;
$fileNameToStore = $filenameWithExt;
$path = $request->file('file_name')->storeAs('public/apkfile/', $fileNameToStore);
$apkstore = Apkfile::find($apk->id);
$apkstore->file_name = $fileNameToStore;
$apkstore->save();
return redirect()->route('admin.apk.index')->with('success', 'Apk Uploaded successfully');
}
else{
return redirect()->route('admin.apk.index')->with('error', 'not upload unsuccessfully');
}

I get this error when trying to verify the email of candidates, Array to String conversion

I have a laravel system that when someone registers, they get a link on their emails where they have to click on it to verify their email. Once they click the link, their information is stored in the users table and the candidates table.
However, values are only inserted in the users table and not the candidates table, and I get the error "Array to string conversion".
Also, the link works well in local host but not after hosting the system.
RegisiterController.php
Str.php`
public function registerCandidate(Request $request){
if(setting('general_enable_candidate_registration')!=1){
return abort(401);
}
$rules = [
'first_name'=>'required',
'last_name'=>'required',
'national_id'=>'required',
'gender'=>'required',
'email'=>'required|email|string|max:255|unique:users',
'date_of_birth_year'=>'required',
'date_of_birth_month'=>'required',
'date_of_birth_day'=>'required',
'categories'=>'required',
'picture' => 'nullable|max:'.config('app.upload_size').'|mimes:jpeg,png,gif',
'cv_path' => 'nullable|max:'.config('app.upload_size').'|mimes:'.config('app.upload_files'),
];
if(setting('general_candidate_captcha')==1){
$rules['captcha'] = 'required|captcha';
}
foreach(CandidateFieldGroup::where('registration',1)->orderBy('sort_order')->get() as $group){
foreach($group->candidateFields as $field){
if($field->type=='file'){
$required = '';
if($field->required==1){
$required = 'required|';
}
$rules['field_'.$field->id] = 'nullable|'.$required.'max:'.config('app.upload_size').'|mimes:'.config('app.upload_files');
}
elseif($field->required==1){
$rules['field_'.$field->id] = 'required';
}
}
}
$this->validate($request,$rules);
$requestData = $request->all();
$password= $request->password;
$requestData['name']= $request->first_name.' '.$request->last_name;
$requestData['display_name'] = $request->first_name;
$requestData['password'] = Hash::make($password);
$requestData['role_id'] = 3;
$fields = CandidateField::get();
//check if email verification is required
if(setting('general_candidate_verification')==1){
do{
$hash = Str::random(30);
}while(PendingUser::where('hash',$hash)->first());
$formData = $_POST;
$formData['name'] = $request->first_name.' '.$request->last_name;
$formData['display_name'] = $request->first_name;
$formData['role_id'] = 3;
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(PENDING_USER_FILES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$formData['picture'] = $file;
}
else{
$formData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = uniqid().'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$formData['cv_path'] = $file;
}
else{
$formData['cv_path'] =null;
}
$pendingUser = PendingUser::create([
'role_id'=>3,
'data'=> serialize($formData),
'hash'=> $hash
]);
//scan for files
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]) && $field->type=='file' && $request->hasFile('field_'.$field->id))
{
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
//dd($name);
$extension = $request->{'field_'.$field->id}->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $pendingUser->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$pendingUser->pendingUserFiles()->create([
'file_name'=>$_FILES['field_'.$field->id]['name'],
'file_path'=>$file,
'field_id'=>$field->id
]);
}
}
//send email to user
$link = route('confirm.candidate',['hash'=>$hash]);
$this->sendEmail($request->email,__('site.confirm-your-email'),__('site.confirm-email-mail',['link'=>$link]));
return redirect()->route('register.confirm');
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $request->date_of_birth_year.'-'.$request->date_of_birth_month.'-'.$request->date_of_birth_day;
$requestData['date_of_birth'] = $dateOfBirth;
//checkfor picture
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(CANDIDATES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$requestData['picture'] = $file;
}
else{
$requestData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$requestData['cv_path'] = $file;
}
else{
$requestData['cv_path'] =null;
}
$user->candidate()->create($requestData);
//save categories
$user->candidate->categories()->attach($request->categories);
//now save custom fields
$customValues = [];
//attach custom values
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]))
{
if($field->type=='file'){
if($request->hasFile('field_'.$field->id)){
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
$extension = $request->{'field_'.$field->id}->extension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$customValues[$field->id] = ['value'=>$file];
}
}
else{
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
}
$user->candidateFields()->sync($customValues);
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
public function confirmCandidate($hash){
//get pending user
$pendingUser = PendingUser::where('hash',$hash)->first();
if(!$pendingUser){
abort(404);
}
$requestData = unserialize($pendingUser->data);
$password = $requestData['password'];
$requestData['password'] = Hash::make($password);
//check for profile picture and move to new directory
if(!empty($requestData['picture']) && file_exists($requestData['picture'])){
$file = basename($requestData['picture']);
$newPath = UPLOAD_PATH.'/'.CANDIDATES.'/'.$file;
rename($requestData['picture'],$newPath);
$requestData['picture'] = $newPath;
}
if(!empty($requestData['cv_path']) && file_exists($requestData['cv_path'])){
$file = basename($requestData['cv_path']);
$newPath = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$file;
rename($requestData['cv_path'],$newPath);
$requestData['cv_path'] = $newPath;
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $requestData['date_of_birth_year'].'-'.$requestData['date_of_birth_month'].'-'.$requestData['date_of_birth_day'];
$requestData['date_of_birth'] = $dateOfBirth;
$user->candidate()->create($requestData);
//save categories
if(isset($requestData['categories'])){
$user->candidate->categories()->attach($requestData['categories']);
}
$fields = CandidateField::get();
$customValues = [];
//attach custom values
foreach($fields as $field){
if($field->type=='file'){
$pendingFile = $pendingUser->pendingUserFiles()->where('field_id',$field->id)->first();
if($pendingFile){
//generate name for file
$name = $pendingFile->file_name;
$info = new \SplFileInfo($name);
$extension = $info->getExtension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$file = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$name;
rename($pendingFile->file_path,$file);
$customValues[$field->id] = ['value'=>$file];
}
}
elseif(isset($requestData['field_'.$field->id])){
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
$user->candidateFields()->sync($customValues);
$pendingUser->delete();
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
`

How to run FFMPEG in laravel project

I can run this code via cmd. And my question is how can I run this command to my laravel project locally and also to my live server?
ffmpeg -i input1.webm -i input2.webm output.mp3
Thanks in advance.
you install the ffmpeg .exe file on your system.
Then you use that code in your application so,first you need to install the application of ffmpeg
public function store(Request $request) {
$rules = [
'title' => 'required',
'description' => 'required',
'meta_title' => 'required',
'category_id' => 'required',
'video_file' => 'required',
'tags' => 'required',
];
$messages = [
'category_id.required' => 'Category field required.',
'tags.required' => 'Tag field required',
];
$validator = Validator::make($request->all(),$rules, $messages);
$validator->sometimes('file', 'nullable|mimes:csv,xlsx|max:1024000', function ($request) {
$messages = ['file.mimes'=>'file type must be csv or xlsx.'];
return ($request->category_id == 2 || $request->category_id == 4);
});
$validator->sometimes('file', 'nullable|mimes:pdf|max:1024000', function ($request) {
$messages = ['file.mimes'=>'file type must be pdf.'];
return ($request->category_id == 1);
});
if($validator->fails()) {
return response()->json(['error'=>$validator->errors(),'status'=>false]);
}else {
DB::beginTransaction();
try {
$formData = new Video();
$formData->title = $request->title;
$formData->user_id = Auth::id();
$formData->description = $request->description;
$formData->upload_date = Carbon::now();
//$formData->meta_title = implode(",",$request->meta_title);
$formData->meta_description =isset($formData->meta_description)?implode(",", $request->meta_description):'';
//$formData->tags = implode(",",$request->tags);
$formData->category_id = $request->category_id[0];
if($request->hasFile('image_file')) {
$uploadedFile = $request->file('image_file');
$filename = time().$uploadedFile->getClientOriginalName();
$imagePath = Storage::disk('public')->putFileAs(
'images',
$uploadedFile,
$filename
);
$formData->image_file = $imagePath;
}
if($request->hasFile('video_file')) {
$uploadedFile = $request->file('video_file');
$filename = trim(time().$uploadedFile->getClientOriginalName());
$removeSpaceFromFile = preg_replace('/[^A-Za-z0-9\-]/', '', $filename);
$filePath = Storage::disk('public')->putFileAs(
'videos',
$uploadedFile,
$removeSpaceFromFile
);
$formData->video_file = $filePath;
$video_id = DB::getPdo()->lastInsertId();
$filefullPath = asset('storage').'/'.$filePath;
$getOutputFilePath = Mp3AndTumbnails::where('id',1)->first();
$outputMp3File = $getOutputFilePath->mp3_output_path;
$outputImageFile = $getOutputFilePath->thumbnails_path;
// $mp3Filename = $video_id.'.mp3';
// $imageFileName = $video_id;
$mp3Filename = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title).'.mp3';
$imageFileName = preg_replace('/[^A-Za-z0-9\-]/', '_',$request->title);
$output = shell_exec('ffmpeg -i '. $filefullPath.' -vn -ar 44100 -ac 2 -ab 192 -f mp3 '. $outputMp3File.'/'.$mp3Filename);
$imageOutput = shell_exec('ffmpeg -i '.$filefullPath.' -ss 00:00:10 -vframes 1 -s 370x220 '.$outputImageFile.'/'.$imageFileName.'.jpg -hide_banner');
$formData->mp3_file = $mp3Filename;
$formData->image_file = 'images/'.$imageFileName.'.jpg';
$dur = shell_exec("ffmpeg -i ".$filefullPath." 2>&1");
preg_match("/Duration: (.{2}):(.{2}):(.{2})/", $dur, $duration);
if(isset($duration[1])) {
$hours = $duration[1];
$minutes = $duration[2];
$seconds = $duration[3];
$video_length = $hours.':'.$minutes.':'.$seconds;
$formData->video_length = $video_length;
}
}
if($request->hasFile('file')) {
$lyricsFile = $request->file('file');
$categoryInfo = Category::where('id',$request->category_id[0])->first();
$filename = time().$lyricsFile->getClientOriginalName();
$lyricsFile->move(public_path("download".'/'.$categoryInfo->name), $filename);
$path = $filename;
$formData->lyrics_file = $path;
}
$formData->save();
foreach ($request->category_id as $key => $value) {
$category = new VideoCategoryUpload();
$category->video_id = $formData->id;
$category->category_id = $value;
$category->save();
}
$updateEncodeVideoId = Video::where('id',$formData->id)
->update(['base64_encode_video_id'=>base64_encode($formData->id)]);
foreach ($request->tags as $key => $value) {
$tagData = new TagModel();
$tagData->user_id = Auth::id();
$tagData->video_id = $formData->id;
$tagData->name = $value;
$tagData->slug_name = $value;
$tagData->save();
}
foreach ($request->meta_title as $key => $value) {
$metaTitleData = new MetaTitleModel();
$metaTitleData->user_id = Auth::id();
$metaTitleData->video_id = $formData->id;
$metaTitleData->title_name = $value;
$metaTitleData->title_slug_name = $value;
$metaTitleData->save();
}
DB::commit();
return response()->json(['status'=>true,'msg'=>'File uploaded successfully !!.']);
}catch(\Exception $e) {
DB::rollback();
return response()->json(['status'=>'exception','msg'=>'Something Went Wrong !!.']);
}
}
}

Image store but not show proper path in laravel API

How can i store actually path in database and how can i fetch image in API?
This is output of API in postman
This is database which show store path of image but its wrong..
public function store(Request $request)
{
$event = $request->all();
if ($request->hasFile('file')) {
$destinationPath = public_path().'/public/img/';
$file = $request->file;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
$input['e_image'] = $fileName;
}
// $return['success'] = true,
// $return['data'] = $event,
// $return['msg'] = "this is message ";
$success['status'] = true;
$success['data'] = [$event];
$success['message'] ="Event created successfully!";
// $success['event'] = $event;
return response()->json($success);
}
$file = new YOURMODELNAME(); please enter your model name in this line of code
public function store(Request $request)
{
$input = $request->all();
$rules = array(
'e_image' => 'required|mimes:jpeg,png,jpg,doc,docx,pdf,mp4,mov,ogg,qt',
'e_group' => required,
'e_invite'=>required,
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
$arr = array("status" => 400, "message" => $validator->errors()->first(), "data" => array());
} else {
try {
$file = $request->file('e_image');
$input['e_image'] = time() . '.' . $file->getClientOriginalExtension();
$destinationPath = public_path('/img/');
$file->move($destinationPath, $input['e_image']);
$file = new YOURMODELNAME();
$file->e_image = $input['e_image'];
$file->e_group = $input['e_group'];
$file->e_invite = $input['e_invite'];
$file->save();
$file->e_image = url('public/img/' . $file->e_image);
$arr = array("status" => 200, "message" => "file upload Successfully", "data" => $file);
} catch (\Exception $ex) {
if (isset($ex->errorInfo[2])) {
$msg = $ex->errorInfo[2];
} else {
$msg = $ex->getMessage();
}
$arr = array("status" => 400, "message" => $msg, "data" => array());
}
}
return \Response::json($arr);
}
please try this one and store image in proper project directory with unique image name .
$img = $request->profile_image;
$old_path = public_path() . "/public/img/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$filename = uniqid() . '.png';
$file = $old_path . $filename;
file_put_contents($file, $image_base64);
if (file_exists(public_path('/public/img/' . $filename))) {
//move image
$new_path = public_path() . "/public/img/newimages/";
if (!is_dir($new_path)) {
mkdir($new_path, 0777, TRUE);
}
$move = File::move($old_path . $filename, $new_path . $filename);
}
//upload image at database
$modalObj = new table();
$modalObj->updateById(\Session::get('table')->id, [
'profile_photo' => $filename,
]);
return response()->json(['code' => '1', 'message' => 'Image Uploaded successfully!!!', 'data' => ['imageName' => url('/public/img/newimages/' . $filename)]]);

Error Message show encountered Severity: Notice Message:

On my controller for development I have added error_reporting(0); just below the opening php tag on my controller. So will not show some errors.
When go to live mode and remove or comment out the added error_reporting(0); I get a couple of errors
A PHP Error was encountered Severity: Notice Message: Undefined
variable: other_sub Filename: common/Filemanager.php
A PHP Error was encountered Severity: Notice Message: Undefined
variable: histSub Filename: common/Filemanager.php
Question: I have those variables defined not sure why errors showing?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//error_reporting(0);
class Filemanager extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('pagination');
$this->lang->load('admin/common/filemanager', 'english');
$this->load->model('admin/tool/model_tool_image');
}
public function index() {
$directory = FCPATH . 'image/catalog/';
$element = $this->input->get('element'); // Element
$input = $this->input->get('input'); // Target
$sub_get = $this->input->get("sub"); // Sub Folders
$end_url = '?';
$end_url .= 'input='.$input;
$end_url .= '&element='.$element;
$endHist = $end_url;
$uris = $this->uri->segment_array();
$sub_folder = "";
if ($sub_get) {
$sub_folder = $sub_get;
}
if ($sub_folder) {
$end_url .= '&sub=' .$sub_folder;
if (sizeof($uris) >3 ) {
for ($i=3; $i < sizeof($uris); $i++) {
$directory .= $uris[$i].'/';
$other_sub .= $uris[$i].'/';
}
$directory .= $sub_folder.'/';
$other_sub .= $sub_folder.'/';
} else {
$directory .= $sub_folder.'/';
$other_sub = $sub_folder.'/';
}
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory.'*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
$per_page = 8;
$segment = $this->input->get('per_page');
$segment += $per_page;
foreach ($images as $key => $image) {
if ($key < $segment && $key >= $segment-$per_page) {
$name = str_split(basename($image), 18);
if (is_dir($image)) {
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(FCPATH .'image/')),
'href' => site_url('admin/filemanager') .'/'. utf8_substr($image, utf8_strlen(FCPATH . 'image/catalog/')),
);
} elseif (is_file($image)) {
$subDirect = 'catalog/'.$other_sub;
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => $subDirect.utf8_substr($image, utf8_strlen($directory)),
'href' => base_url() . 'image/' . utf8_substr($image, utf8_strlen(FCPATH . 'image/catalog/'))
);
}
}
}
$data['title'] = "Image Manager";
$data['heading_title'] = "Image Manager";
if (isset($sub_folder)) {
$data['directory'] = $this->uri->segment(3) .'/'. $this->uri->segment(4);
} else {
$data['directory'] = '';
}
if ($element) {
$data['element'] = $element;
} else {
$data['element'] = "";
}
if ($input) {
$data['target'] = $input;
} else {
$data['target'] = "";
}
$endRep = $end_url == '?' ? '' : rtrim($end_url,'&');
// Sets go to previous parent folder.
if ($other_sub) {
$arraySub = explode('/', rtrim($other_sub,'/'));
unset($arraySub[sizeof($arraySub) -1]);
$histSub = "";
foreach ($arraySub as $one) {
$histSub .= $one.'/';
}
$endHist .= "&sub=".$arraySub[sizeof($arraySub) - 1];
}
// Parent folder link
$data['parent'] = site_url('admin/filemanager') .'/'. $histSub . $endHist;
// Refesh current Page
$data['refresh'] = current_url().$endRep;
$config['base_url'] = base_url('admin/filemanager/') .'/'. $other_sub.$endRep;
$config['end_url'] = $end_url == '?' ? '' : rtrim($end_url,'&');
$config['total_rows'] = $image_total;
$config['per_page'] = $per_page;
$config['page_query_string'] = TRUE;
$config['num_links'] = "16";
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] ="</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
return $this->load->view('template/common/filemanager_view', $data);
}
}
Problem now solved I had to change a few things and make the input->get setup a lot more simple now works fine.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Filemanager extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->library('pagination');
$this->lang->load('admin/common/filemanager', 'english');
$this->load->model('admin/tool/model_tool_image');
}
public function index() {
$input_get_directory = $this->input->get('directory');
$input_get_page = $this->input->get('page');
$input_get_filter = $this->input->get('filter_name');
$input_get_target = $this->input->get('target');
$input_get_thumb = $this->input->get('thumb');
if (isset($input_get_filter)) {
$filter_name = $input_get_filter .'/';
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
if (isset($input_get_page)) {
$page = $input_get_page;
} else {
$page = 1;
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
// Split the array based on current page number and max number of items per page of 10
$images = array_splice($images, ($page - 1) * 16, 16);
foreach ($images as $image) {
$name = str_split(basename($image), 14);
if (is_dir($image)) {
$url = '';
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => site_url('admin/common/filemanager' . '?&token=' . $this->session->userdata('token') . '?&directory=' . utf8_substr($image, utf8_strlen(FCPATH . 'image/' . 'catalog/')) . $url)
);
} elseif (is_file($image)) {
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(FCPATH . 'image/')), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => base_url() . 'image/' . utf8_substr($image, utf8_strlen(FCPATH . 'image/'))
);
}
}
$data['heading_title'] = "Image Manager";
$data['text_no_results'] = "No Results";
$data['text_confirm'] = "Are You Sure";
$data['entry_search'] = "Search..";
$data['entry_folder'] = "New Folder";
$data['button_parent'] = "Parent";
$data['button_refresh'] = "Refresh";
$data['button_upload'] = "Upload";
$data['button_folder'] = "New Folder";
$data['button_delete'] = "Delete";
$data['button_search'] = "Search";
// Session token for ajax
$data['token'] = $this->session->userdata('token');
if (isset($input_get_directory)) {
$data['directory'] = $input_get_directory;
} else {
$data['directory'] = '';
}
// Return the filter name
if (isset($input_get_filter)) {
$data['filter_name'] = $input_get_filter;
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($input_get_target)) {
$data['target'] = $input_get_target;
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($input_get_thumb)) {
$data['thumb'] = $input_get_thumb;
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($input_get_directory)) {
$pos = strrpos($input_get_directory, '/');
if ($pos) {
$url .= '?&directory=' . substr($input_get_directory, 0, $pos);
}
}
$data['parent'] = site_url('admin/common/filemanager' .'?&token='. $this->session->userdata('token') . $url);
// Refresh
$url = '';
if (isset($input_get_directory)) {
$url .= '?&directory=' . $input_get_directory;
}
$data['refresh'] = site_url('admin/common/filemanager' .'?&token='. $this->session->userdata('token') . $url);
$this->load->view('template/common/filemanager_view', $data);
}
}

Resources