ltdev
ltdev

Reputation: 4457

file uploading and creating upload folders with Codeigniter

I'm having this function inside my Album_Model:

public function upload($album_id, $album){
        $album= strtolower($album);

        $upload_config = array(
            'upload_path'   =>  './uploads/'.$album,
            'allowed_types' =>  'jpg|jpeg|gif|png',
            'max_size'      =>  '2000',
            'max_width'     =>  '680',
            'max_height'    =>  '435', 
        );

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

        // create an album if not already exist in uploads dir
// wouldn't make more sence if this part is done if there are no errors and right before the upload ??
        if (!is_dir('uploads')) {
            mkdir('./uploads', 0777, true);
        }
        if (!is_dir('uploads/'.$album)) {
            mkdir('./uploads/'.$album, 0777, true);
        }

        if (!$this->upload->do_upload('imgfile')) { 
            // upload failed
            return array('error' => $this->upload->display_errors('<span>', '</span>'));
        } else {
            // upload success
            $upload_data = $this->upload->data();
            return true;
        }
    }

So what this basicly does is to upload images to an album. Also if the folder album does not exist already, it creates a new album.

I was doing some tests and found out something that might be a small bug. While I was forcing my form to do some invalid upload attempts and the upload fails, as expected, but the album folder (suppose the album folder doesn't exist) is still created.

Whouldn't make more sence to create the album folder if there are no erros and right before uploading the image and if yes how can I fix this??

Upvotes: 1

Views: 24064

Answers (3)

Ema4rl
Ema4rl

Reputation: 588

THE ACCEPTED ANSWER IS NOT THE RIGHT WAY!!!

The right way is to extend the Upload library

The code:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * File Uploading Class Extension
 *
 * @package     CodeIgniter
 * @subpackage  Libraries
 * @category    Uploads
 * @author      Harrison Emmanuel (Eharry.me)
 * @link        https://www.eharry.me/blog/post/my-codeigniter-upload-extension/
 */
class MY_Upload extends CI_Upload {

    /**
     * Validate Upload Path
     *
     * Verifies that it is a valid upload path with proper permissions.
     *
     * @return  bool
     */
    public function validate_upload_path()
    {
        if ($this->upload_path === '')
        {
            $this->set_error('upload_no_filepath', 'error');
            return FALSE;
        }

        if (realpath($this->upload_path) !== FALSE)
        {
            $this->upload_path = str_replace('\\', '/', realpath($this->upload_path));
        }

        if ( ! is_dir($this->upload_path))
        {
            // EDIT: make directory and try again
            if ( ! mkdir ($this->upload_path, 0777, TRUE))
            {
                $this->set_error('upload_no_filepath', 'error');
                return FALSE;
            }
        }

        if ( ! is_really_writable($this->upload_path))
        {
            // EDIT: change directory mode
            if ( ! chmod($this->upload_path, 0777))
            {
                $this->set_error('upload_not_writable', 'error');
                return FALSE;
            }
        }

        $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/',  $this->upload_path);
        return TRUE;
    }
}


How to use:

Simply create application/libraries/MY_Upload.php and paste the code above in it. That's all!


More info:


NOTE:

This extension is compatible with CodeIgniter 3.x and 2.x versions.

Upvotes: 1

Kumar V
Kumar V

Reputation: 8840

You have set a flag for checking the directory existence. I have changed your code to make it work as per your need.

<?php

public function upload($album_id, $album)
{
    $album = strtolower($album);

    $upload_config = array('upload_path' => './uploads/' . $album, 'allowed_types' =>
        'jpg|jpeg|gif|png', 'max_size' => '2000', 'max_width' => '680', 'max_height' =>
        '435', );

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

    // create an album if not already exist in uploads dir
    // wouldn't make more sence if this part is done if there are no errors and right before the upload ??
    if (!is_dir('uploads'))
    {
        mkdir('./uploads', 0777, true);
    }
    $dir_exist = true; // flag for checking the directory exist or not
    if (!is_dir('uploads/' . $album))
    {
        mkdir('./uploads/' . $album, 0777, true);
        $dir_exist = false; // dir not exist
    }
    else{

    }

    if (!$this->upload->do_upload('imgfile'))
    {
        // upload failed
        //delete dir if not exist before upload
        if(!$dir_exist)
          rmdir('./uploads/' . $album);

        return array('error' => $this->upload->display_errors('<span>', '</span>'));
    } else
    {
        // upload success
        $upload_data = $this->upload->data();
        return true;
    }
}

?>

Upvotes: 6

Renier
Renier

Reputation: 1535

The way you have it it will always make the directory if it does not exist.

To answer your question.. yes, it would make more sense, to create the folder right before uploading.

Try putting this:

if (!is_dir('uploads')) {
    mkdir('./uploads', 0777, true);
        }
if (!is_dir('uploads/'.$album)) {
    mkdir('./uploads/'.$album, 0777, true);
        }

Inside this:

if (!$this->upload->do_upload('imgfile')) { 
        // upload failed
        return array('error' => $this->upload->display_errors('<span>', '</span>'));
    } else {
        // put if statements here.
        // upload success
        $upload_data = $this->upload->data();
        return true;
    }

So it would look like this:

if (!$this->upload->do_upload('imgfile')) { 
        // upload failed
        return array('error' => $this->upload->display_errors('<span>', '</span>'));
    } else {
        if (!is_dir('uploads')) {
        mkdir('./uploads', 0777, true);
    }
    if (!is_dir('uploads/'.$album)) {
        mkdir('./uploads/'.$album, 0777, true);
    }
        // upload success
        $upload_data = $this->upload->data();
        return true;
    }

If I understand you correctly this should do what you want.

Hope it helps.

Upvotes: 0

Related Questions