EllisLab text mark
Advanced Search
     
file uploading with text and description
Posted: 10 November 2012 12:40 AM
Avatar
Joined: 2011-02-09
102 posts

I am almost through building a simple gallery, but need help on the logic.
The gallery is using code from the CI file upload series.

I basically have a form that displays title, description, and image field to upload an image. I have already set up where the image uploads to a directory and makes a thumb on the server. That was not to difficult.

Now I am trying to upload a title and description with an image id stored in the db.
The image id will have to be joined with the title and description id.

I will also add validation to prevent sql injection.

So, what are the steps(logic) to assign id to an image. Store the images. Relate the title and description id to the image id. So when the gallery is viewed, the title and description will be next to the correct corresponding image.

Here is the page where the title and description will be next the image
http://www.cradlewebdesign.com/index.php/gallery/index

Thanks.


Controller

<?php
class Gallery extends CI_Controller {
 
 
function index() {
  
  $this
->load->model('Gallery_model');
  
  
  
  if (
$this->input->post('upload')) {
   $this
->Gallery_model->do_upload();
  
}
  
  $data[
'images'$this->Gallery_model->get_images();
  
$data['title'$this->input->post('title');
  
$data['title'$this->input->post('description');  
  
  
  
$data['left_content''gallery_left';
  
$data['right_content''gallery_right';
  
$this->load->view('includes/template'$data);
 
}

Model

<?php
class Gallery_model extends CI_Model {
 
 
var $gallery_path;
 var 
$gallery_path_url;
 
 function 
Gallery_model() {
  parent
::__construct();
  
  
$this->gallery_path realpath(APPPATH '../images');
  
$this->gallery_path_url base_url().'images/';
 
}
 
 
function do_upload() {
  
  $config 
= array(
   
'allowed_types' => 'jpg|jpeg|gif|png',
   
'upload_path' => $this->gallery_path,
   
'max_size' => 2000
  
);
  
  
$this->load->library('upload'$config);
  
$this->upload->do_upload();
  
$image_data $this->upload->data();
  
  
$config = array(
   
'source_image' => $image_data['full_path'],
   
'new_image' => $this->gallery_path '/thumbs',
   
'maintain_ration' => true,
   
'width' => 150,
   
'height' => 100
  
);
  
  
$this->load->library('image_lib'$config);
  
$this->image_lib->resize();
  
 
}
 
 
function get_images() {
  
  $files 
scandir($this->gallery_path);
  
$files array_diff($files, array('.''..''thumbs'));
  
  
$images = array();
  
  foreach (
$files as $file{
   $images []
= array (
    
'url' => $this->gallery_path_url $file,
    
'thumb_url' => $this->gallery_path_url 'thumbs/' $file
   
);
  
}
  
  
return $images;
 
}
 

View

<div id="upload">
  
<?php
  
echo form_open_multipart('gallery');
  
//userfile is from file upload library
  
echo form_input("title""title");
  
?>
        
<br />
        
<?php
  
echo form_textarea("description""website description""200""200");
  
?>
        
<br />
        
<?php
  
echo form_upload('userfile');
  echo 
form_submit('upload''Upload');
  echo 
form_close();
  
?>  
 
</div
 Signature 

What you cry about today, you will rejoice about tomorrow.-Kenneth E. Hagin

 
Posted: 10 November 2012 01:09 AM   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2011-02-09
102 posts

I just found http://ellislab.com/forums/viewthread/222115/

I will see if this answered my question.

 Signature 

What you cry about today, you will rejoice about tomorrow.-Kenneth E. Hagin

 
Posted: 10 November 2012 08:42 AM   [ # 2 ]   [ Rating: 0 ]
Avatar
Joined: 2012-10-23
61 posts

I created some time ago a simple upload form with:
- Name field for image.
- Description field image.
- Field for the file.

So when it was submited:
- It uploaded the image, checked if the image was uploaded correctly, then creates thumbnail(optional).
- If the first step worked, then takes the image name, the description, and the random name generated if it was set to insert those data in the DB.

I don’t have the code here rigth now but that is the main idea, if you need more help ask wink

PD:Sorry for my english.

 
Posted: 11 November 2012 01:18 AM   [ # 3 ]   [ Rating: 0 ]
Avatar
Joined: 2011-02-09
102 posts

Here is my model. I am able to easily store the title and description, but I cannot get the path and thumb path to be stored in the db. The problem is under function store_images_db.

<?php
class Gallery_model extends CI_Model {
 
 
var $gallery_path;
 var 
$gallery_path_url;
 
 function 
Gallery_model() {
  parent
::__construct();
  
  
$this->gallery_path realpath(APPPATH '../images');
  
$this->gallery_path_url base_url().'images/';
 
}
 
 
function do_upload() {
  
//set image configuration
  
$config = array(
   
'allowed_types' => 'jpg|jpeg|gif|png',
   
'upload_path' => $this->gallery_path,
   
'max_size' => 2000,
   
'encrypt_name'  => true
  
);
  
  
$this->load->library('upload'$config);
  
$this->upload->do_upload();
  
$image_data $this->upload->data();
  
  
//set image path and make thumb
  
$config = array(
   
'source_image' => $image_data['full_path'],
   
'new_image' => $this->gallery_path '/thumbs',
   
'maintain_ration' => true,
   
'width' => 150,
   
'height' => 100
  
);
  
  
$this->load->library('image_lib'$config);
  
$this->image_lib->resize();
  
 
}
 
 
function store_images_db() {
  
  $this
->db->insert('photos', array(
     
'id' => $this->input->post('id'),
     
'title' => $this->input->post('title'),
     
'description' => $this->input->post('description'),
     
'path' => $image_data['full_path'],
     
'thumb_path'=> $image_data['file_path''thumbs/'$image_data['file_name']
  
  
//'path' => $image_data['full_path'],
  //'thumb_path' => $image_data[
)); 
 
}
 
 
function get_images() {
  
  $files 
scandir($this->gallery_path);
  
$files array_diff($files, array('.''..''thumbs'));
  
  
$images = array();
  
  
//loop images in view
  
foreach ($files as $file{
   $images []
= array (
    
'url' => $this->gallery_path_url $file,
    
'thumb_url' => $this->gallery_path_url 'thumbs/' $file
   
);
  
}
  
  
return $images;
 
}
 
 Signature 

What you cry about today, you will rejoice about tomorrow.-Kenneth E. Hagin

 
Posted: 11 November 2012 05:42 AM   [ # 4 ]   [ Rating: 0 ]
Avatar
Joined: 2012-10-23
61 posts

Hi again Stephen, yur code looks similar to the one I use, the main diference is I do not store the path into DB.

I use.

Paths variables. You can pass and them to your model with getter&setter;. But i dont think its a real cause.

Private $upload_path='./assets/images/galerias/'
Private 
$upload_path_thumbs='./assets/images/galerias/thumbs/'

If you wan i can post my code but it doesnt store the paths, only the id, name, description and the random name generated at the upload.

Wich is the error when you try to store the path??

 
Posted: 11 November 2012 01:49 PM   [ # 5 ]   [ Rating: 0 ]
Avatar
Joined: 2011-02-09
102 posts

If you wan i can post my code but it doesnt store the paths, only the id, name, description and the random name generated at the upload.

If you can show me you code that would be great. Come to think of it, there is no point storing the path, because if the path changes, then the paths in the database will be wrong.

 Signature 

What you cry about today, you will rejoice about tomorrow.-Kenneth E. Hagin

 
Posted: 11 November 2012 04:31 PM   [ # 6 ]   [ Rating: 0 ]
Avatar
Joined: 2012-10-23
61 posts

Hi again, I’ve some of my code here i’ll put some parts maybe it can help you.

You are right. If the path is changed it would be a mess to change all the records of the database, so I prefer create a variable for the galleries and define their path, so all of them can be saved in their own directory (If you use some kind clasification like carsgallery, moviesgallery….)

Paths variables.

Private $upload_path='./assets/images/galerias/'
Private 
$upload_path_thumbs='./assets/images/galerias/thumbs/'

Now the upload code. In MY_Model(or MY_Controller, i think is better in model) cause was used by many of them.

// Upload Function
    // Returns $image_data['file_name'] if the upload of the image and its thumb was correct or it will return errors to the controller.
    
public function subir_archivo($upload_path$upload_path_thumbs){
        
        
//empieza la subida del archivo  
        
$config = array(
                
'upload_path' => $upload_path,
                
'allowed_types' => 'gif|jpg|png|jpeg',
                
'max_size' => 1024*2,
                
'max_width' => 1000// for example
                
'max_height' => 1000// for example
                
'remove_spaces' => true,
                
'encrypt_name' => true
             
);
        
        
$this->load->library('upload'$config);
                
        if ( ! 
$this->upload->do_upload())
        
{
            $data 
$this->upload->display_errors();
            
            
$datos= array (
                
                
'file_name' => '',
                
'error' => true,
                
'data_error' => $data,              
              );
              
            return 
$datos;
        
}else{
            $image_data
$this->upload->data();
            
            
$config = array (
                 
'source_image' => $image_data['full_path'],
                 
'allowed_types' => 'gif|jpg|png|jpeg',
                 
'new_image' => $upload_path_thumbs,
                 
'maintain_ration' =>  true,
                 
'width' => 150// choose yourself
                 
'height' => 100 // choose yourself
                 
);
        
            
$this->load->library('image_lib'$config);
            
$this->image_lib->resize();
                
            
            
$datos= array (
                    
'file_name' => $image_data['file_name'],
                    
'error' => false
                    
);
            
            return 
$datos;
        
        
}
        
    } 

So now the call that launchs the image upload

$subida=$this->subir_archivo($this->upload_path$this->upload_path_thumbs);

 
$image_name=$subida['file_name'];
 
$error=$subida['error'];

 if(
$error==true){
 $data[
'error'$subida['data_error'];
 
}

 
if ($error==false){

      $datos 
= array (
      
'titleImg' => $this->input->post('title'true),
      
'descriptionImg' => $this->input->post('description'true),
      
'img' => $image_name,
      );

 
$this->db->insert('galeria_imagenes'$datos);

 

This should be enough for your needs.
This should work (in fact it works actually in a web) but its for single upload, If you need multiple upload at the same time the code have to be revised.

For multiple there are some alternatives, I use a code that uses twitter bootstrat and CI.

Hope the code helps.

 

 
Posted: 11 November 2012 11:07 PM   [ # 7 ]   [ Rating: 0 ]
Avatar
Joined: 2011-08-08
533 posts

@Stephen

I read your codes.
And I noticed you broke the MVC rule.
Some of your methods like do_upload() should not be in the model.
It should be in the controller or library.

And catching the data from a form is supposed to be in the controller as well,
not in the model.

The codes that should be in the model/MY_Model is the CRUD.
C = Create record
R = Read record
U = Update record
D = Delete record

Also before diving into a project.
You should have a plan. Try to visualize everything first.
And use the Divide and conquer method.
You can use flowchart but if you are in a hurry you can use the comments method.

Here is a basic example of ‘Comment Method’,

controller:
  - catch data
  - validate data
  - upload image
  - resize image

model:
  - store info like img_id, title, image_name, description
view:
  - display upload form
  - display error message
  - display successful upload page


I also have another solution, there are already made Image Galleries where you can incorporate to your site easily, like the one below so you don’t re-invent the wheel,
http://inspirationfeed.com/resources/tools/top-15-handy-jquery-image-gallery-plugins/

Anyways if your purpose is to practice your coding skills while making your gallery then stick
with your custom gallery plan.

 Signature 

Stick with it, practice it and have fun with it.

 
Posted: 11 November 2012 11:20 PM   [ # 8 ]   [ Rating: 0 ]
Avatar
Joined: 2011-08-08
533 posts

Here is another way to visualize your plan for your codes using the ‘Comment method’.

Step 1 - Display Upload Form (view)
Step 2 - validate data from controller (controller)
    - If it has error display form again with error
Step 3 - Capture valid data (controller)
Step 4 - resize image for thumbnail (controller)
Step 5 - store images into image_path/image_folder (controller)
step 6 - When everything is right then store information into DB. (model)
    - When record insert is successful return to controller
Step 7 - If insert record is a success display ‘Success Message’ (view)
etc, etc, etc…

The key to right coding is to plan it ahead.
(Visualize it, you can use flowchart or Comment method).
Do it step by step, you can modify the steps above if it doesn’t meet your needs.

Hope this will help you stephen.

 Signature 

Stick with it, practice it and have fun with it.

 
Posted: 12 November 2012 03:51 AM   [ # 9 ]   [ Rating: 0 ]
Avatar
Joined: 2011-02-09
102 posts

@jojo777
Thank you so much for the example. I think I now see that I just need to set the image path as a variable and simply pass to the database. I just need to tweak a couple things.
I will post my finished code soon.

@solid9
You are God sent man. I should plan better next time. I only planned a few of the steps you mentioned. I hurried because of the lack of time I have to do what I love, programming. When you manage a well known restaurant, there is not much time for anything else.
I will take what you said to heart, plan efficiently, and re-arrange the code in its proper place (MVC) and post soon. Thank you for your time.

 Signature 

What you cry about today, you will rejoice about tomorrow.-Kenneth E. Hagin

 
Posted: 12 November 2012 07:43 AM   [ # 10 ]   [ Rating: 0 ]
Avatar
Joined: 2011-02-09
102 posts

I organized the code, but cannot get it to work at all now.
It is not displaying the photos on the server or storing the photo path in the db.

These are the errors I am getting:

Undefined variable: data

Filename: controllers/gallery.php

Line Number: 64

&

Undefined variable: image_data

Filename: models/gallery_model.php

Line Number: 12

<?php
class Gallery_model extends CI_Model {
 
 
 
 
function store_image_db($data{
  
  $data 
= array(
       
'id' => $this->input->post('id'),
       
'title' => $this->input->post('title'),
       
'description' => $this->input->post('description'),
       
'path' => $image_data['full_path'],
       
'thumb_path'=> $image_data['file_path''thumbs/'$image_data['file_name']
  
 
); 
  
   
$this->db->insert('photos'$data);
 
}
 
 
 
<?php
class Gallery extends CI_Controller {
 
  
var $gallery_path;
  var 
$gallery_path_url;
 
 function 
index() {
  
  
  $this
->load->model('Gallery_model');
  
  
$this->gallery_path realpath(APPPATH '../images');
  
$this->gallery_path_url base_url().'images/';
  
  
//Step 2: // Is the form being submitted?
  
if ($this->input->post('upload')) {
  
  
//Step 3: image configuration
  
$config = array(
   
'allowed_types' => 'jpg|jpeg|gif|png',
   
'upload_path' => $this->gallery_path,
   
'max_size' => 2000,
   
'encrypt_name'  => true
  
);
  
  
$this->load->library('upload'$config);
  
   
//Step 4: Set the validation rules.
            
$this->form_validation->set_rules(array(
                array(
                    
'field' => 'title',
                    
'label' => 'Title',
                    
'rules' => 'required',
                ),
                array(
                    
'field' => 'description',
                    
'label' => 'Description',
                    
'rules' => 'required',
                ),
            ));

            
// Step 5: Run validation
            
if ($this->form_validation->run())
            
{
  
  
  
  $this
->upload->do_upload();
  
//Step 6: Capture image upload data
  
$image_data $this->upload->data();
  
  
//Step: 7 Resize captured image data
  
$config = array(
   
'source_image' => $image_data['full_path'],
   
'new_image' => $this->gallery_path '/thumbs',
   
'maintain_ration' => true,
   
'width' => 150,
   
'height' => 100
  
);
  
  
$this->load->library('image_lib'$config);
  
$this->image_lib->resize();
  
  
$this->Gallery_model->store_image_db($data);
  
  
//Step 8: Set image paths files var to data array
  
$data['images'= array(
  
   
$files scandir($this->gallery_path),
   
$files array_diff($files, array('.''..''thumbs'))
  );
  
  
$images = array();
  
  
//Step 9: Loop image data set to var images
  
foreach ($files as $file{
   $images []
= array (
    
'url' => $this->gallery_path_url $file,
    
'thumb_url' => $this->gallery_path_url 'thumbs/' $file
   
);
  
}
  
  
return $images;

   
   
$data['left_content''gallery_left';
   
$data['right_content''gallery_right';
   
$this->load->view('includes/template'$data);
  
 
}
  
  
   
   
  
  }
 }

 Signature 

What you cry about today, you will rejoice about tomorrow.-Kenneth E. Hagin

 
Posted: 12 November 2012 07:42 PM   [ # 11 ]   [ Rating: 0 ]
Avatar
Joined: 2011-08-08
533 posts

controller: partial codes only

<?php
class Gallery extends CI_Controller {

 
//Data type declaration
 
var $gallery_path;
 var 
$gallery_path_url;
 
    function 
__construct() {
        parent
::__construct();
  
  
//load classes
  
$this->load->model('Gallery_model');
  
  
//variable data assignment
  
$this->gallery_path realpath(APPPATH '../images');
  
$this->gallery_path_url base_url().'images/';
    

Where is your step 1?

model:

<?php
class Gallery_model extends CI_Model {
 
 
 
function store_image_db($data{
  
   $data 
= array(
     
'id' => $this->input->post('id'),
     
'title' => $this->input->post('title'),
     
'description' => $this->input->post('description'),
     
'path' => $image_data['full_path'],
     
'thumb_path'=> $image_data['file_path''thumbs/'$image_data['file_name']
   
  
); 
   
     if(
$this->db->insert('photos'$data)
     
{
   
return TRUE;
  
}
  
else
  
{
   
return FALSE;
  
}
 }
 

Also I don’t think putting your image_upload codes inside the index is a good idea.
Better create a custom name for the image_upload method.

 

 

 Signature 

Stick with it, practice it and have fun with it.