Upload and Insert File Data in CodeIgniter - mysql

I'm creating a file upload system in CodeIgniter, and I have a form that asks for a file name before it uploads to the database. It uses my controller to upload the file to the server. Currently the controller is working, but I need to insert the file name into the table.
upload.php:
function do_upload()
{
$config['upload_path'] = './gfiles/';
$config['allowed_types'] = 'gif|jpg|jpeg|bmp|png|psd|pdf|eps|ai|zip|indd|qxt';
$config['encrypt_name'] = 'TRUE';
//$config['max_size'] = '100';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->db->insert('files', $_POST);
}
}
Does anyone have any pointers on how to get the file name into the database properly? The code above also encrypts the filename. Thank you.

$data = array('upload_data' => $this->upload->data()); should contain what you are looking for.
do print_r($data) and you should see the original and encrypted filename.

Related

Ajax format after submit - Laravel

I'm working on project, I faced some problems
If I fill all fields and then submit there is no problem and it saved to database, but my issue if some field is empty the validation messages error appear in another page as JSON format.
I don't use any AJAX code in my view file.
Here is controller code:
public function store(RegisterRequest $request){
$user = User::create($request->all());
$user->password = Hash::make($request['password']);
if ($request->file('avatar')) {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
} else {
$path = $user->avatar;
}
$user->avatar = $path;
$user->save();
return redirect()->route('admin.user.index')->with('message','User created successfully');
And here is RegisterRequest code:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed',
'country_code' => 'sometimes|required',
'phone'=>Rule::unique('users','phone')->where(function ($query) {
$query->where('country_code', Request::get('country_code'));
})
];
Can you help me please?
Your errors should be accessible inside blade file with $errors variable which you need to iterate and display the errors.
Link to doc which will help you with the render part - https://laravel.com/docs/7.x/validation#quick-displaying-the-validation-errors
Clearly from doc as well
If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
https://laravel.com/docs/7.x/validation#creating-form-requests
Also refactor the code a bit as following to run only one query to create a user instead of creating and then updating.
public function store(RegisterRequest $request){
if ($request->hasFile('avatar')) {
//use try catch for image conversion might be a rare case of lib failure
try {
$image = $request->file('avatar');
$destinationPath = base_path() . '/public/uploads/default';
$path = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
$image_resize = Intervention::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save($destinationPath . '/' . $path);
$request->avatar = $path;
} catch(\Exception $e){
//handle skip or report error as per your case
}
}
$request['password'] = Hash::make($request['password']);
$user = User::create($request->all());
return redirect()->route('admin.user.index')->with('message','User created successfully');
}

Create custom url links in code igniter

I have searched all over the internet for information that would help me achieve this seemingly simple thing.
But I can't get my hands on any that is helpful.
What I want to do is to create a custom url link like http://mywebsite.com/users/username,
where
1) 'users' is a MySQL table name
2) 'username' is a column name.
I did some digging on the internet and found this code on github:
<?php
//check for referal links
function referal()
{
$CI =& get_instance();
$cookie_value_set = $CI->input->cookie('_tm_ref', TRUE) ? $CI->input->cookie('_tm_ref', TRUE) : '';
if ($CI->input->get('ref', TRUE) AND $cookie_value_set == '') {
// referred user so set cookie to ref=username
$cookie = array(
'name' => 'ref',
'value' => $CI->input->get('ref', TRUE),
'expire' => '7776000',
);
$CI->input->set_cookie($cookie);
return TRUE;
}elseif ($cookie_value_set == '') {
$cookie = array(
'name' => 'ref',
'value' => 'sso',
'expire' => '15552000',
);
$CI->input->set_cookie($cookie);
return TRUE;
}elseif ($cookie_value_set != '') {
//already referred so ignore
return TRUE;
}else{
return TRUE;
}
}
//end of hooks file
?>
The owner of the gist only mentioned saving the file as referral.php inside the hook folder. This is not helping me with what I want to achieve, I don't know how to use the code:
1. How do I pass the referrer field to the variable username from the users table?
2. How do I load the hook file to view (register.php)?
3. How and where do I call the hook file?
So can anybody give me an insight?

Codeigniter Image uploading not working on live server

I have a situation where a user uploads his/her trip photos. They are saved in a folder and also supposed to be in database. Situation is: my code is working perfectly on localhost, and many other servers, but not on the server I want. Though it uploads files successfully, but the query is not executed which is supposed to save file path in database. I am stuck in this problem from more than a week. The same code works in other places. Here is my controller:
public function trip_photos(){
$this->load->model('UserModel');
$this->load->model('CommentModel');
$this->load->library('session');
print_r($_FILES);
$logged_session = $this->session->userdata('login');
if($logged_session == 1) {
$this->load->model('TripModel');
$this->load->model('UserActivityModel');
$uid = $this->session->userdata('uid');
$tid = $this->input->post('tid');
foreach($_FILES as $key => $image_upload){
$upload = self::upload_trip_photo($key);
if($upload['status']){
$this->TripModel->add_trip_photo($uid, $tid, $upload['file']);
}
}
$this->UserctivityModel->add_user_photo($uid, $tid);
}else{
redirect('/');
}
}
private function upload_trip_photo($image){
$msg = '';
$config['upload_path'] = './assets/images/trip/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['file_name'] = parent::getGUID();
$this->load->library('upload', $config);
if ($this->upload->do_upload($image))
{
$data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = "./assets/images/trip/" . $data['file_name'];
$resize['create_thumb'] = TRUE;
$resize['maintain_ratio'] = TRUE;
$resize['width'] = 222;
$resize['thumb_marker'] = '';
$resize['new_image'] = "./assets/images/trip/thumbnails/" . $data['file_name'];
$this->image_lib->resize();
$this->image_lib->clear();
$this->image_lib->initialize($resize);
if($this->image_lib->resize()){
$status = true;
$msg = $data['file_name'];
}else{
$status = false;
}
}
else
{
$status = false;
}
#unlink($_FILES[$image]);
return array('status' => $status, 'file' => $msg);
}
when I enabled CI_Profiler, it says that only 2 out of 3 query executed on the server I want it to work. But the same profiler suggests that 3 of 3 queries executed on localhost or other servers. Its so confusing.
Please note that I already have checked the following:
File Upload: On
upload_raw_post_data: On
selinux permissions: disables (mine is centos)
File permissions: 777
php memory_limit: 128 MB
max_size: 8 MB
var_dump, print_r, echo all not working or displaying any information from controller.
somehow, this in above code: $upload = self::upload_trip_photo($key); is not giving it back the file path it requires. Can anybody help please? #DFriend
UPDATED Turns out that in the localhost are other servers where its working, this array is returned by the function upload_trip_photo to the $upload variable:
Array ( [image0] => Array ( [name] => maintour3.jpg [type] => image/jpeg
[tmp_name] => D:\xampp\tmp\php2539.tmp [error] => 0 [size] => 200491 ) )
array(2) { ["status"]=> bool(true) ["file"]=> string(36)
"E3965DFC8B265CEFF522A1EC43B33E34.jpg" }
while in the server where its not working, only this array is returned:
Array ( [image0] => Array ( [name] => mg7.jpg [type] => image/jpeg
[tmp_name] => /tmp/phpNcCnX0 [error] => 0 [size] => 28460 ) )
It means this statement in the upload_trip_photo() function:
return array('status' => $status, 'file' => $msg);
is not returning the requested array, with file name and status. And why? I am totally clueless.
Help Please!
Thankfully this worked after extensive debugging. The line
if($this->image_lib->resize()){
$status = true;
$msg = $data['file_name'];
}else{
$status = false;
}
was not working. Later when I set it to display_error() method, it showed that my server did not support GD library. This is an essential library to manipulate Graphics. So, the query was not being executed, as the $status variable was set to false.
I recompiled my php with GD Library module. And bigno! its working now.
Thanks for staying with me. :)

JSON response assign to $var then save to db

I'm using Dropzone.js to upload multiple files in Laravel, which works fine uploads to my uploads folder but now I want the save the json object to the db.
Currently I have:
$file = Input::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/userfiles', $fileName);
return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));
So now how would I store this in my users table in the uploads column?
Depends what you want to store...
As I understand it, you want to associate uploads with a user? If you just want to store the filename, which may suffice, maybe do this:
// models/User.php
class User extends Eloquent {
// ...
public function setFilesAttribute(array $files)
{
$this->attributes['files'] = json_encode(array_values($files));
}
public function getFilesAttribute($files)
{
return $files ? json_decode($files, true) : array();
}
}
// Your script
$file = Input::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/userfiles', $fileName);
$user = User::find(1); // Find your user
$user->files[] = $fileName; // This may work, not too sure if it will being a magic method and all
$user->files = array_merge($user->files, [$fileName]); // If not, this will work
$user->save();
return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));
Something like this?
Of course, you could get more complex and create a model which represents a "file" entity and assign multiple files to a usre:
// models/File.php, should have `id`, `user_id`, `file_name`, `created_at`, `updated_at`
class File extends Eloquent {
protected $table = 'files';
protected $fillable = ['file_name']; // Add more attributes
public function user()
{
return $this->belongsTo('User');
}
}
// models/User.php
class User extends Eloquent {
// ...
public function files()
{
return $this->hasMany('File');
}
}
// Your script
$file = Input::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads/userfiles', $fileName);
$user = User::find(1); // Find your user
$file = new File([
'file_name' => $fileName,
// Any other attributes you want, just make sure they're fillable in the file model
]);
$file->save();
$user->files()->attach($file);
return Response::json(array('filelink' => '/uploads/userfiles/' . $fileName));

File upload with text fields in codeigniter using upload class

I have a form in which there are both types of fieldsmeans inputs text , radio , select , textarea and file upload fields.
I am using the same form for insert and edit.
My problem is that i have to upload file and insert the data in the table.
Controller functions
function myUploadwithInsert(){
if($category = $this->input->post())
{
$this->load->library('form_validation');
if(!$this->imageUpload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('my_view', $error);
}else{
$this->form_validation->set_rules('name', 'Category Title', 'trim|required');
if ($this->form_validation->run() == TRUE)
{
if ($id = $this->categories_model->create($category))
{
redirect('admin/categories');
}
}else{
$this->load->view('my_view');
}
}
}else{
$this->load->view('my_view');
}
}
public function uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
return false;
}
else
{
$data = $this->upload->data();
return $data;
}
}
Now the problem is that if image is uploaded and there come a form input error form will be displayed again user rectifies the form fields and fills the image field again. Then the image will be uploaded again.
The same thing goes when i define the input condition first and then upload the same problem rises. How can i ivercome this problem? Is there anyother way to do this task.
After a little research i have found a solution here
Using Codeigniter Form Validation Library
http://codeigniter.com/user_guide/libraries/form_validation.html
And
http://keighl.com/post/codeigniter-file-upload-validation
A great article. Solver my problem