Uploading image to with custom name in Yii framework - php

I am trying to upload images from registration form in Yii framework. The image will be saved in "img/avatar" folder and the name of the image should be changed to the username. The piece of code I use for this is below:
//uploading avatar to the img/avatar folder
$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$personModel->picture = $upload_file;
$picture_name = $userModel->username;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name);
}
$personModel->save();
//end of image uploading part
The problem is: the name of the username has been saved in picture row of the database. But the image was not uploaded to the folder. I am trying to find out the problem in the code. but cannot solve it. Any suggestions?

Well first thing you need to do is to prevent database input if the picture is not saved.
if(isset($uploadedfile))
{
if($upload_file->saveAs(Yii::app()->basePath.'/../img/avatar'.$picture_name)
{
$personModel->save();
}
else
{
//throw error
}
}
As far as problems in the code go. Most common problem is directories not existing, path to them not being correct.

$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$ext = pathinfo($upload_file->picture, PATHINFO_EXTENSION);
$picture_name = $userModel->username . '.' . $ext;
$personModel->picture = $picture_name;
if(isset($upload_file))
{
$upload_file->saveAs('/Your_correct_path/.../etc/'.$picture_name);
}
$personModel->save();

$upload_file = CUploadedFile::getInstance($personModel, 'picture');
$picture_name = $userModel->username . '.' . pathinfo($upload_file, PATHINFO_EXTENSION);
$personModel->picture = $picture_name;
if (isset($upload_file)) {
$upload_file->saveAs(Yii::app()->basePath . '/../img/avatar/' . $picture_name);
}
$personModel->save();
You have to check your folder permission.

The problem has been solved through following code:
$uploadFile = CUploadedFile::getInstance($personModel, 'picture');
$extension = pathinfo($uploadFile, PATHINFO_EXTENSION);
$fileName = $userModel->username . '.' . $extension;
if (isset($uploadFile)) {
$personModel->picture = $fileName;
$uploadFile->saveAs(Yii::app()->basePath . '/../img/avatar/' . $fileName);
}

Related

Image Upload is not working in a Laravel Project hosted in a shared server

I have deployed a Laravel project in a shared hosting. I have changed my .env file and copied all files from the public folder to the main directory and deleted the public folder. Now the problem is, whenever I am trying to upload an image, I am getting an internal server error. I suppose the problem is the Image Intervention is not getting the right folder to save the image. I have tried the both ways given below:
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('/images/admin/' . $filename);
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
and
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = '/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
But None of these is working. Any possible Solution?
Use laravel base_path function, so your code will look like this
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = base_path().'/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
Answer Update
Issue was fileinfo extension missing or disbaled.
Try This.
use Storage;
use File;
if(!empty($request->file('admin_pro_pic')))
{
$file = $request->file('admin_pro_pic') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$admin->image=$fileName;
}
Create imges inside public directory.
I am handling it like this:
// check for defined upload folder inside .env file, otherwise use 'public'
$publicUploadDir = env('UPLOAD_PUBLIC', 'public/');
// get file from request
$image = $request->file('admin_pro_pic');
// hasing is not necessary, but recommended
$new['path'] = hash('sha256', time());
$new['folder] = 'images/admin/';
$new['extension'] = $file->extension();
// store uploaded file and retrieve path
$image->storeAs($publicUploadDir, implode($new, '.'));

get error while file upload in laravel

I am trying to upload image in laravel. But when i upload it gives error.
Call to a member function getClientOriginalExtension() on null
Here is my Blade file form
{{Form::open(array('url' => '/AddNewBlog','id'=>'blogadd' ,
'method' => 'post','class'=>'form-row','files'=>true,
"enctype"=>"multipart/form-data"))}}
And here is controller
$imagename_bg = time() . '.' . $photo->getClientOriginalExtension();
$destinationPath = public_path('/uploads/blog');
$thumb_img = Image::make($photo->getRealPath())->resize(750, 450);
$thumb_img->save($destinationPath . '/' . $imagename_bg, 80);
$photo->move($destinationPath, $imagename_bg);
Please help me how to resolve this problem.
I am not able to understand your code. if you are looking for uploading image and resize using intervention package try this:-
if($request->hasFile('blogimage')){
if (Input::file('blogimage')->isValid()) {
$file = Input::file('image');
$img = Image::make($file);
$img->resize(400,270);
$name = pathinfo($_FILES['image']['name']);
$destination = public_path('/uploads/blog');
$ext = $name['extension'];
$rand= time().str_random(6).date('h-i-s').'.'.$ext;
$img->save($destination.$rand);
}
}
Or Without intervention pacakge:-
if($request->hasFile('blogimage')){
if (Input::file('blogimage')->isValid()) {
$file = Input::file('blogimage');
$destination = public_path('/uploads/blog');
$ext= Input::file('blogimage')->getClientOriginalExtension();
$mainFilename =time().str_random(5).date('h-i-s');
$file->move($destination, $mainFilename.".".$ext);
}
}
Hope it helps!
$photo = $request->file('file_name');
You only need to use this:
$photo = $request->file("blogimage");
instead of:
$photo = $request->input("blogimage")
Hope this will fixed your problem!

Delete image after upload new one

I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:
//Save logo
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/logos/');
$request->file('logo')->move($location, $filename);
$oldFilename = $general_Settings->logo;
$general_Settings->logo = $filename;
Storage::delete($oldFilename);
}
$general_Settings->save();
for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.
what do you think is issue of that?
Solved:
The issue was Filesystem.php I made my local root set to 'root' => public_path('avatars/'), and changed all my functions in my app because no way to save images in sub-folders and delete them just can save in sub-folders.
then my update function become like this:
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = 'sitelogo' . '-' . time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/');
$request->file('logo')->move($location, $filename);
$general_Settings->logo = $filename;
}
$general_Settings->save();
I hope this help someone.
Since, You have stored logo file name only not full path of file,
You need to give full path from public folder to delete image. Change delete line as:
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/logos/');
$request->file('logo')->move($location, $filename);
$oldFilename = $general_Settings->logo;
$file_path = "avatars/logos/".$oldFilename;
$general_Settings->logo = $filename;
Storage::delete($file_path);
}
$general_Settings->save();
This might work.

move_uploaded_file() in php returns true but file not found inside the directory

Please i need help on this.
I was uploading an image to my server using the move_uploaded_file() method, the method returns true bu the uploaded file was not found inside the specified directory on my server. i have checked thoroughly, searched for the file on the server in case it was uploaded to another directory, checked the permission on the directory but all seems perfect. i really dont know what went wrong .
Here is the snippet of the code.
$uploaddir = './upload_dir/';
$allowed = array('gif', 'png', 'jpg','bmp');
$filename = $_FILES['uploadfile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$data = array();
if (!in_array($ext, $allowed)) {
$data['status'] = 'error';
$data['error_message'] = 'Invalid file type';
}
else{
$file_name = time() . '_' . uniqid() . '_' . basename($_FILES['uploadfile']['name']);
$file_name = preg_replace('/[^a-z0-9_\.\-]+/i', '_', $file_name);
$file = $uploaddir . $file_name;
if (isset($_FILES['uploadfile']['tmp_name']) && move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$data['status'] = 'success';
$data['file_name'] = $file_name;
} else {
$data['status'] = 'error';
}
echo json_encode($data);
}
Thanks in advance.
Please use is_uploaded_file($_FILES['uploadfile']['tmp_name']) instead of isset($_FILES['uploadfile']['tmp_name']) for security reason check here
And for the upload dir use $uploaddir = $_SERVER['DOCUMENT_ROOT'] . "/upload_dir/"; instead of $uploaddir = './upload_dir/'; to get absolute path instead of relative one.
thanks everyone. I gave the wrong permission to the folder. that seems to be the problem for my own case.

Saving a remote image from facebook graph api

Any idea what's wrong?
I end up with 1bytes files and they are wrong. Using Intervention Image & PHP. Tried many ways to get it but nothing... If I just want to display it works but I can't save the picture...
$avatar_url = 'http://graph.facebook.com/' . $id . '/picture?type=square&width=140&height=140&redirect=false';
$avatar_pic_url = json_decode(file_get_contents($avatar_url), true)['data']['url'];
dd($avatar_pic_url);
$avatar = Image::make($avatar_pic_url);
$extension = 'jpg';
// save it
$destinationPath = 'uploads/avatars/';
$filename = uniqid(). '.' . $extension;
$path_to_temp_image = $avatar->dirname . '/' . $avatar->filename;
$key = $destinationPath . $filename;
// Upload avatar to remote storage
$uploadSuccess = Storage::put($key, $path_to_temp_image);

Categories