codeigniter: loading variables and view from within model - php

I'm building an image uploading script (for the first time) in Codeigniter and the way I have it is that if the image upload form gets validated it performs the following code in a model:
public function upload($id) //function to handle the initial image upload before crop
{
$config['image_library'] = 'gd2';
$config['source_image'] = '/path/to/image/mypic.jpg';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$config['upload_path'] = 'images/uploads/temp/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$file_data = $this->upload->data();
if ( ! $this->upload->do_upload() )//the default parameter of do_upload() is 'userfile' (meaning the name of the form input)
{
$error = '<p>Upload failed!</p> <p>Please make sure the image is in a .jpg, .gif or .png format and that it\'s no larger than 1028 x 768 pixels in dimension. Also it can\'t be more than 2MBs in size. If this problem persists, please contact webmaster#dreamsy.org.</p>';
$this->session->set_flashdata('error', $error);
redirect(base_url().'community/upload_image');
}
else
{
$image_path = base_url().'images/uploads/temp/'.$file_name;
//$data = array( 'upload_data' => $this->upload->data() );
//$this->load->view('community/upload_success');
$this->load->helper('form', 'url');
$vars['id'] = $this->uri->segment(3);
$vars['$image_path'] = $image_path;
$vars['$file_data'] = $file_data;
$this->load->vars($vars);
$this->template->write_view('content', 'community/upload_success');
$this->template->render();
}
}>template->render(); //template library
But when I call the variables that are loaded (via load->vars()) they don't get loaded and when the page loads I get "undefined variable" errors. I suspect it's not possible to pass variables from a model to the view even when the view is loaded from within the model as I have done above. Or maybe I'm just doing something incorrectly (as I'm a bit of a n00b).
Would you even take this route? Would it make more sense to pass the variables to the controller and then to load the view from the controller? Or something else I haven't considered at all? lol
Any help is greatly appreciated. Thanks in advance.
*edit:
I also have the $image_path variable inside of an

Would you even take this route? Would it make more sense to pass the variables to the controller and then to load the view from the controller? Or something else I haven't considered at all?
Yeah, generally speaking it is somewhat accepted to have your views talk directly to the model and vice versa but only when using a presentation layer. In the case of CI, I think it's best to have all the data loaded in from your controller to your view when you render the view like this:
$this->load->view('your-view', $data);
To pass the vars from the model to the controller you can call methods on your model like this:
// Your_Model is the class name of your model
// your_model is the variable name it gets injected into
$this->load->model('Your_Model','your_model');
$data['some_data'] = $this->your_model->get_some_data();
To define those getters in your model, you define a function like this:
function get_some_data()
{
return $this->some_data;
}
That way you create an API into your data, and you can have the getter retrieve whatever you will need in the format you will need it in.

Assuming the line:
$this->load->vars($vars);
is where you want to load your view, then it should be:
$this->load->view('nameofview', $vars);

Related

why the load function is not working in codeigniter

This code is not working not only this but when ever i use the this->load->library('email') or something its showing error as
"message": "Undefined property: App\\Controllers\\Epicureser1::$load",
this is the code which i used currently
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload',$config);
The code your are showing there is not a part of Codeigniter 4 but Codeigniter 3.
That was the old way of uploading a file. If uploading a file is what you are trying to achived that can be done by using the IncomingRequest Class.
$files = $request->getFiles();
// Grab the file by name given in HTML form
if ($files->hasFile('uploadedFile'))
{
$file = $files->getFile('uploadedfile');
// Generate a new secure name
$name = $file->getRandomName();
// Move the file to it's new home
$file->move('/path/to/dir', $name);
echo $file->getSize('mb'); // 1.23
echo $file->getExtension(); // jpg
echo $file->getType(); // image/jpg
}
That is not really a Library. If by any chance what you're looking for is how to load libraries in Codeigniter 4, that is actually pretty easy. Let's say you want to use the Email Library.
First you should configure your email settings on app/Config/Email.php
To send an email your just need to access the email service:
$email = \Config\Services::email();
$email->setFrom('your#example.com', 'Your Name');
$email->setTo('someone#example.com');
$email->setCC('another#another-example.com');
$email->setBCC('them#their-example.com');
$email->setSubject('Email Test');
$email->setMessage('Testing the email class.');
$email->send();
Now let's say what you want is to create a custom library, for that you should create your class inside your app/Libraries folder.
<?php
namespace App\Libraries;
class Custom
{
public function myFunction()
{
return true;
}
}
Now to load this library so you can use it's functions you should do the following.
$custom = new \App\Libraries\Custom();
$giveMeTrue = $custom->myFunction();
Like Vilar said in one of his comments:
If you're using Codeigniter 4, the super object $this, which was used
for loading every kind of library, models, etc... has been removed.
You should take a look at
codeigniter.com/user_guide/installation/upgrade_4xx.html even it's not
fully complete it will guide you through main changes.

How to Display Existing User Pictures In Codeigniter.?

I have a complete php script which i bought from codecanyon and the Author does not support costum work... it was made with Codeigniter framework and its working fine and perfectly but the script does not support
Ability for User to Upload Profile Image
Ability for uploaded image be shown in profile page.
3 Ability to ReUpload and or delete image.....
I have search google for it and could not find answers to this.
I have tried Creating >Upload-Controller > Upload View > Upload
Model, which only upload to a specified folder in a specific url e.g site.com/uploadimage.
I want to ask if there is any way to integrate this feature to the system... Am a php newbie.
Many Thank in Advance...
I hope this can help you.
Create this folder path for uploading the image : app_data/images/account/
// Your Controller
Class User extends CI_Controller
{
// This upload method
function upload_user_photo()
{
$path = 'app_data/images/account/';
if(!file_exists($path))
{
mkdir($path, 0777, true);
}
$file_name = increment_string('image_profile', '-'); //use codeigniter string helper
$config['upload_path'] = $path;
$config['file_name'] = $file_name;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
//Take an action if photo has been uploaded
if($this->upload->do_upload('image'))
{
$upload_data = $this->upload->data();
// View response from upload data
echo "<pre>";
print_r ($upload_data);
echo "</pre>";
// Array key is column name of your table
$data =
[
'user_id' => 'insert our user id',
'photo' => $upload_data['file_name']
];
//Take action save to your model
$this->load->model('your_model_name');
$this->your_model_name->save_profile_image($data);
}
}
}
#Model
Class Your_model_name extends CI_Model
{
function save_profile_image($data)
{
$this->db->insert($data);
}
}
Read more about codeigniter upload setting preferences

Use do_upload function with hardcoded image location (Codeigniter)

My problem is following. I'm writing this test data seed file. I already have all functionalities wrote (creating thumbnalins, hd, watermarking img, etc...) so now I would like just to reuse this code, but with some hardcoded image data location.
$imgToUploadLocation = "../../static/img/test.jpg";
$_FILE['userfile'] = imgToUploadLocation;
$config['upload_path'] = '/pictures/';
$config['allowed_types'] = 'jpeg|jpg';
$config['remove_spaces'] = true;
$config['max_size'] = '25000';
$config['encrypt_name'] = true;
$this->upload->initialize($config);
if ($this->upload->do_upload()) {
echo "finaly!";
} else {
echo "error";
}
The problem is that however i specify my image location i will always get error you did not select any image to upload.
I wonder how to use upload library without view form? If you need any additional informations please let me know and I will provide. Thank you!
This is not the proper way of defining. Files are expected in a certain way on the $FILES global variable to be uploaded.
In order to define the file you want to upload do:
$_FILES['userfile']['name'] = 'what name you want';
$_FILES['userfile']['tmp_name'] = $imgToUploadLocation;
Read more about the $_FILES in https://secure.php.net/manual/en/features.file-upload.post-method.php

Grocery Crud - Set the allowed file types in upload field

My question is similar to this one http://www.grocerycrud.com/forums/topic/169-allowed-types-for-file-upload/
The answer there is no longer updated.
how can I set allowed types for file upload in grocery crud with the version 1.4?
Could the file types be set directly from the function? Something like this one:
$crud->set_upload_file_types('jpg','apk');
Thanks
At this moment you can not change it directly from the controller function.
But you can change it from the config file at your application/config/grocery_crud.php
$config['grocery_crud_file_upload_allow_file_types'] = 'gif|jpeg|jpg|png|tiff|doc|docx|txt|odt|xls|xlsx|pdf|ppt|pptx|pps|ppsx|mp3|m4a|ogg|wav|mp4|m4v|mov|wmv|flv|avi|mpg|ogv|3gp|3g2|apk';
I had the same issue (i could easily do what Jawaad said, but i needed to define file types for each field). Here is my solution:
https://github.com/scoumbourdis/grocery-crud/pull/290/files
Sent a pull request to GroceryCrud, if they choose to use it or not is upto them.
Refer to the commit msg for instructions (https://github.com/scoumbourdis/grocery-crud/pull/290)
i tried another solution and it is working
$crud->set_field_upload("image","assets/uploads/team","jpg|png");
it just to add the allowed file types like in my code separated by '|'
Works 100% in Grocery Crud and Codeigniter version 3
you'd configure your
in the folder
application/config/grocery_crud.php
$config['grocery_crud_file_upload_allow_file_types'] = 'gif|jpeg|jpg|png|tiff|doc|docx|txt|odt|xls|xlsx|pdf|ppt|pptx|pps|ppsx|mp3|m4a|ogg|wav|mp4|m4v|mov|wmv|flv|avi|mpg|ogv|3gp|3g2|apk';
With $crud->set_field_upload("image","assets/uploads/team","jpg|png"); you cant overide at all , it picks extension from above grocery_crud.php.
Finally in your controller ,this is my example :
function __construct() {
parent::__construct();
$this->load->driver('session');
$this->load->database();
$this->load->helper('url');
$this->load->library('grocery_CRUD');
$this->load->model('Generic');
$this->load->library('upload');
$this->load->helper(array('form','url'));
//$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|rar|zip';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
}
public function index() {
$crud = new grocery_CRUD();
...
//dondt forget to set some configuration of visibily from your crud pages where you want your Upload Input appears like...
$crud->fields("file_url" ...
$crud->add_fields("file_url"..
$crud->edit_fields("file_url"..
....
$crud->set_field_upload('file_url','assets/uploads/files');
$output = $crud->render();
....
}

setting $this->data in a method then gets unset

I am uploading an image with codeigniter, and in the method I am doing the following,
if(isset($_FILES['product_image']['name'])) {
//some setup needed
$config['upload_path'] = "./media/images/products";
$config['allowed_types'] = "png|gif|jpg|jpeg";
$config['max_width'] = 1490;
$config['max_height'] = 400;
//make sure the library is running with clean config
$this->upload->initialize($config);
//do the upload
if(!$this->upload->do_upload('product_image')){
$this->data['image_error'] = $this->upload->display_errors();
$this->template->build('/admin/products/create', $this->data);
} else {
$this->data['image_data'] = $this->upload->data();
//die(print_r($this->data));
$this->template->build('/admin/products/create', $this->data);
}
}
so basically I check to see if there is something in the $_FILES and then upload if there is assigning $this-data['image_data'] with the upload data along the way. However when I come to process the data i.e. save the filename in a database, I cannot access $this->data['image_data'] below is how I am trying to use it,
if($this->input->post("submit_create") == "Save") {
die(print_r($this->data['image_data']));
}
however I get the following error,
Message: Undefined index: image_data
why is this I though assigning things to $this made them accessible not just throughout the method but the entire controller?
I think, when you are printing image_data at this point in your example:
if($this->input->post("submit_create") == "Save") {
die(print_r($this->data['image_data']));
}
You should actually be using $image_data instead:
if($this->input->post("submit_create") == "Save") {
die(print_r($image_data));
}

Categories