Skip to content
Advertisement

Codeigniter Multi Save Upload Path

I try to save the uploaded file in 2 paths, one inside a folder and contain the id and one outside the folder

Here’s my code :

private function _uploadImage()
{
    $config['upload_path']          = './upload/'.$this->product_id;
    $config['allowed_types']        = 'gif|jpg|png';
    $config['file_name']            = $this->product_id;
    $config['overwrite']            = true;
    $config['max_size']             = 1024; // 1MB
    
    $config['upload_path']          = './upload/product';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['file_name']            = $this->product_id;
    $config['overwrite']            = true;
    $config['max_size']             = 1024; // 1MB
    
    if (!is_dir('upload/'.$this->product_id)) {
        mkdir('./upload/' . $this->product_id, 0777, TRUE);
    }

    $this->load->library('upload', $config);

    if ($this->upload->do_upload('image')) {
        return $this->upload->data("file_name");
    }
    
    return "default.jpg";
}

When I run that code, the result is stucked

Can you help me what’s wrong?

Advertisement

Answer

You set the upload_path key twice, which just overwrites itself. You’ll need to process the upload wholly twice, with your two directories different.

Since you’re using a private function, you could for example add a parameter that distinguishes the path

private function _uploadImage($path)
{
    $config['upload_path']          = $path . '/' . $this->product_id;
    $config['allowed_types']        = 'gif|jpg|png';
    $config['file_name']            = $this->product_id;
    $config['overwrite']            = true;
    $config['max_size']             = 1024; // 1MB
    
    if (!is_dir($path . $this->product_id)) {
        mkdir($path . $this->product_id, 0777, TRUE);
    }

    $this->load->library('upload', $config);

    if ($this->upload->do_upload('image')) {
        return $this->upload->data("file_name");
    }
    
    return "default.jpg";
}

Now when you call your function, just include the paths:

$this->_uploadImage('./upload');
$this->_uploadImage('./upload/product');
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement