Upload Image to DB

I’m posting this by request from this thread;

It is usually recommended to store images in a server folder rather than in a database, but for small image files it can be preferable for ease and perhaps performance (see here) to store in them in the db. There may be a simple way to do this with ActiveRecord, but using Data Access Object (DAO) as shown below worked for me.




// View

 <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

 <?= $form->field($image, 'org_image')->fileInput() ?>

        // button and end form




// Model

    //Validation rule

['org_image', 'file', 'extensions' => 'jpg, jpeg, gif, png', 'maxFiles' => 1, 'maxSize' => 1024 * 64, 'skipOnEmpty' => true, 'on' => 'org_image'],


   //Method for upload

public function handleForm() {

        if($_FILES['Image']['size']['org_image'] > 0) {

            $fileName = $_FILES['Image']['name']['org_image'];

            $tmpName  = $_FILES['Image']['tmp_name']['org_image'];

            $fileSize = $_FILES['Image']['size']['org_image'];

            $fileType = $_FILES['Image']['type']['org_image'];


            $content = fopen($tmpName, 'r');


            if(!get_magic_quotes_gpc())

            {

                $fileName = addslashes($fileName);

            }

            

            $q = 'INSERT INTO image (org_image, org_type, org_size) VALUES (:content, :type, :size)';

            $cmd = Yii::$app->db->createCommand($q);

            $cmd->bindValue(':content', $content, PDO::PARAM_LOB);

            $cmd->bindValue(':type', $fileType, PDO::PARAM_STR);

            $cmd->bindValue(':size', $fileSize, PDO::PARAM_INT);

            $cmd->execute();

            return $this;

        } 

    }




// Controller

if ($image->load(Yii::$app->request->Post()) && $image->handleForm()) {

       //  return redirect ...

} else {

       //  return render form ...



Mimetype checking is pretty important, especially where users are able to upload something. While the Yii filetype restriction uses pathinfo to get the extension, there are situations where even a valid ‘file.jpg’ can contain malicious code. The pathinfo protects you from null-bytes on the file name to trick it to accept say a php file when it requires a jpg. However you can add PHP code inside a valid image.

I would think that you would want to make the form as secure as possible when saving it into the database.

I have actually abandoned this approach and am now storing all images to file. I’m also using sadovojav/imagecutter extension, and so most of the validation is covered by the exension. Thanks for the information.