How to run FFMPEG in laravel project - laravel-5

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 !!.']);
}
}
}

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

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

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

Data is not inserted into database using codeigniter

I have a form where user insert their basic details and after submitting form it will redirect on view page. I trying to submit it redirect on view page without inserting data into database. I debug my code of controller I come to know that $request = $this->getRequest(); code in $request I am getting GET [ 1 ] and post is empty and in if condition here used $this->getRequest()->isPost() to check whether that post is true or false. Please find screenshot of code of controller.
Controller function
public function addAction() {
$captcha = new Zend_Session_Namespace('captcha');
$captcha->captcha = session_id();
$request = $this->getRequest();
if ($this->getRequest()->isPost()) {
if ($form->isValidPartial($request->getPost())) {
$dataform = $request->getPost();
$alphabet =
"abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$randomPassword = implode($pass); //turn the array into a string
$dataform['password'] = $randomPassword;
if ($dataform['vercode'] != $_SESSION["vercode"]) {
$msg = "Please enter a correct code!";
$this->view->assign('errorMessage', $msg);
return FALSE;
}
if ($dataform['sessionCheck'] != $captcha->captcha) {
$this->view->assign('errorMessage', CSRF_ATTACK);
return FALSE;
}
if($dataform['name'] == 2 && $dataform['statename'] == 0){
$this->view->assign('errorMessage', 'Please select state
for the state officials!');
return;
}
$Contactusobj = new Application_Model_User;
$countdata = $Contactusobj-
>checkuserclient($dataform['username']);
$countemail = $Contactusobj-
>checkemail($dataform['email']);
if(($countdata == 0)){
$match = $Contactusobj->insertuserdetails($dataform);
$description = 'Add New User </br>';
if($dataform[name] && $dataform[name] != 0){
$rolename = $Contactusobj-
>getuserrolename($dataform[name]);
$description .= '<span>Role:
</span>'.$rolename.'</br>';
}
if($dataform[ministry_name] && $dataform[ministry_name]
!= 0){
$ministryname = $Contactusobj-
>Getministryname($dataform[ministry_name]);
$description .= '<span>Ministry:
</span>'.$ministryname .'</br>';
}
if($dataform[statename] && $dataform[statename] != 0){
$statename = $Contactusobj-
>getuserstatename($dataform[statename]);
$description .= '<span>State:
</span>'.$statename.'</br>';
}
if($dataform[cityname] && $dataform[cityname] != 0){
$cityname = $Contactusobj-
>getdistrictname($dataform[cityname]);
$description .= '<span>City:
</span>'.$cityname.'</br>';
}
$description .= '<span>User Name:
</span>'.$dataform[username].'</br>';
$description .= '<span>First Name:
</span>'.$dataform[firstname].'</br>';
$description .= '<span>Last Name:
</span>'.$dataform[lastname].'</br>';
$description .= '<span>Email:
</span>'.$dataform[email].'</br>';
$description .= '<span>Mobile:</span>'.$dataform[mobile];
$auditlog = array("uid" => $userid->userid,
"application_type" => 'User',
"description" => $description
);
$auditobj = new Application_Model_Auditlog;
$auditobj->insertauditlog($auditlog);
/***************audit log end by braj***************/
$mailObj = new Zend_Mail();
$username = $dataform['username'];
$fname = ucfirst($dataform['firstname']);
$weblink = WEB_LINK;
$body = MESSAGE_BODY;
$body = str_replace('{user_name}',$username,$body);
$body = str_replace('{fname}',$fname,$body);
$body =
str_replace('{user_password}',$dataform['password'],$body);
$body = str_replace('{web_link}',$weblink,$body);
$subject= MAIL_SUBJECT;
$to =$dataform['email'];
$from =MAIL_FROM;
$name = MAIL_NAME;
$mailObj->setSubject($subject);
$mailObj->setBodyHtml($body);
$mailObj->addTo($to, $name);
$mailObj->setFrom($from,
$name);//print_r($mailObj);die();
$mailObj->send();
$this->_redirect('/user/add?actmsg=add');
}else{
if($countdata){
$this->view->assign('errorMessage', 'Your
username is already exists in the database.');
return;
} }}}}}}}
Model User.php
public function insertuserdetails($dataform) {
$userid = new Zend_Session_Namespace('userid');
$user_table = new Zend_Db_Table('dbt_users');
$date = date("Y-m-d H:i:s");
$datainsert = "";
$datainsert = array(
'state' => $dataform['statename'],
//'cityname'=> $dataform['cityname'],
'ministry_name' => $dataform['ministry_name'],
'username' => $dataform['username'],
'password' => hash_hmac('sha256', $dataform['password'], ''),
'firstname' => $dataform['firstname'],
'lastname' => $dataform['lastname'],
'organisation' => '',
'mobile' => $dataform['mobile'],
'email' => $dataform['email'],
'telephone' => '',
'address' => '',
'role' => $dataform['name'],
'upload' => '',
'dateAdded' => $date,
'dateModify' => $date,
'status' => 1,
'created_by' => $userid->userid,
'login_time' => 1,
'tmp_password' => md5(uniqid(rand(), TRUE)) . substr(md5($dataform['username']), 2, 10),
'reset_time' => $date
);
$insertdata = $user_table->insert($datainsert);
return $insertdata; }

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 column 'picture' cannot be null

My initial question was posted wrong so i'm reposting it. I am practicing with a tutorial on tutsplus by joost van veen and i added an image upload to the controller but every time i try to save a post i get an error from database saying column 'picture' cannot be null. I've checked other answers but nothing explains the problem. Any help would be appreciated.
MY CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_from_post(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}
MY_MODEL
public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
}
return $data;
}
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
RULES TO SET FORM VALIDATION
public $rules = array(
'pubdate' => array(
'field' => 'pubdate',
'label' => 'Publication date',
'rules' => 'trim|required|exact_length[10]'
),
'title' => array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required|max_length[100]'
),
'slug' => array(
'field' => 'slug',
'label' => 'Slug',
'rules' => 'trim|required|max_length[100]|url_title'
),
'content' => array(
'field' => 'content',
'label' => 'Content',
'rules' => 'trim|required'
),
'picture' => array(
'field' => 'picture',
'label' => 'Upload File',
'rules' => 'trim'
),
);
public function get_new() {
$article = new stdClass();
$article->title = '';
$article->category_id = '';
$article->slug = '';
$article->content = '';
$article->picture = '';
$article->pubdate = date('Y-m-d');
return $article;
}
I fixed the problem by creating a new method array_me() in the model and calling it in the controller.
NEW METHOD IN MY_MODEL
public function array_me($fields) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
$data['picture'] = $picture;
}
return $data;
}
EDITED CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_me(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}

Resources