Solved

Uploading Multiple images to database as BLOB (Codeigniter)

Posted on 2013-12-03
1
3,836 Views
Last Modified: 2013-12-18
I have been able to upload one image to the database (however I am unsure how to upload two images as a BLOB in the database under the field columns 'imageone' and 'imagetwo'. I know its something to do with an Array, I have changed the view to:

     Image One <input name="image[]" type="file" />
     Image Two <input name="image[]" type="file" />
     
But I'm not sure what is need in the controller to enable it to upload both images into the mydatabase.mytable as a BLOB.

Here is what I have so far, controller:
(This is what I used when only imageone inserted successfully, I assume the upload_images function needs a change of code)

public function index()
	{

//index controller code etc here

 $this->upload_images($id);

}

      	private function upload_images($id){
		
		
				ini_set('memory_limit','512M');
				ini_set('max_input_time','480'); 
				ini_set('max_execution_time','480');
		
				if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST")
		{
			$image_error = '';
			$path = str_replace('regions/www','regions/uploads',$_SERVER["DOCUMENT_ROOT"]);
			$path .= '/';
			$valid_formats = array("jpg", "png", "gif", "jpeg");
			$entry =  array_shift(array_keys($_FILES));
			$name = $_FILES[$entry]['name'];
			$size = $_FILES[$entry]['size'];
			if(strlen($name))
			{
				list($txt, $ext) = explode(".", $name); 
				$ext = strtolower(trim($ext));
				if(in_array($ext,$valid_formats))
				{
					if($size<(1024*1024))
					{
						$imagename = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
						
							
						switch ($_FILES[$entry]['type']) {
							case 'image/png' :
								$imagecreatefn = 'imagecreatefrompng';
								$imagefn = 'imagepng';
								break;
									
							case 'image/gif' :
								$imagecreatefn = 'imagecreatefromgif';
								$imagefn = 'imagegif';
								break;
									
							case 'image/jpeg' :
							case 'image/pjpeg' :
							default :
								$imagecreatefn = 'imagecreatefromjpeg';
								$imagefn = 'imagejpeg';
								break;
						}
								$upload_info = getimagesize($_FILES[$entry]['tmp_name']);
								$width = $upload_info[0];
								$height = $upload_info[1];
								$whratio = $width/$height;
								// make thumbnail
								$mwidth = 200;
								$mheight = 50;
								$mwhratio = $mwidth/$mheight;

								if ($whratio > $mwhratio)
								{
									$newwidth = $mwidth;
									$newheight = $mwidth/$whratio;
								}else
								{
									$newheight = $mheight;
									$newwidth = $mheight*$whratio;
								}
								$resized_img = imagecreatetruecolor($newwidth,$newheight);
								$new_img = $imagecreatefn($_FILES[$entry]['tmp_name']);
								imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
								if ($imagefn($resized_img, $path.'t_'.$imagename))
								{

									$mwidth = 595;
									$mheight = 110;
									if ($width > $mwidth || $height > $mheight)
									{
										// make new image
										$mwhratio = $mwidth/$mheight;
											
										if ($whratio > $mwhratio)
										{
											$newwidth = $mwidth;
											$newheight = $mwidth/$whratio;
										}else
										{
											$newheight = $mheight;
											$newwidth = $mheight*$whratio;
										}
											
								$resized_img = imagecreatetruecolor($newwidth,$newheight);
								$new_img = $imagecreatefn($_FILES[$entry]['tmp_name']);
								imagecopyresampled($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
								$imagefn($resized_img, $path.$imagename);
									} else
									{
										move_uploaded_file($_FILES[$entry]['tmp_name'], $path.$imagename);
									}
							
							
							$sizes = getimagesize($path.$imagename);
							$t_sizes = getimagesize($path.'t_'.$imagename);
							$contents = file_get_contents($path.$imagename);
							$t_contents = file_get_contents($path.'t_'.$imagename);
										
						$contents = 	$this->db->escape_str($contents);
					$update = "UPDATE mydatabase.mytable set imageone = '$contents'
          						  WHERE id = ".$id;
								$this->db->query($update);							
							
						
							$file_info = getimagesize($path.$imagename);
							$height = $file_info[1];
							$t_file_info = getimagesize($path.'t_'.$imagename);
							$t_height = $t_file_info[1];
					
							
							
														} else {
							$image_error = "Upload was not successful - please note image file maximum size is 1 MB";
						}
					} else
					{
						$image_error = "Image file maximum size is 1 MB";
					}
				} else
				{
					$image_error = "Sorry, format '$ext' isn't supported";
				}
						} else {
				$image_error = 'No filename was specified';
			}
			//$this->load->view('view_success');
               
		}
		
            }

Open in new window


1) Please can someone suggest me how I can pass each individual image to an array and pass both images to the database under the correct field (imageone and imagetwo)?

2) Is it possible to resize each images (different sizes) before inserting

Apologies, I am new to codeigniter.


Thank you
0
Comment
Question by:Jon C
1 Comment
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39693044
You're into fairly advanced territory here, and the question is so broad that it is sort of like "How do I build a web site?"  Broad to the point that the answer might be, "Go to college and study web development."  But that said, I can help you with some of the parts.

Recommend that you do not store the image blobs in the data base.  Store big things like that in the file system and just store the URL pointers in the data base.  If you follow that advice you will thank me later, I promise.

Here is an upload-and-resize script.  I am not familiar with CodeIgniter, but you can probably understand the principles demonstrated here.  As you learn more about CodeIgniter, you should be able to apply these principles.  Please read it over, especially the comments and man page references, and post back with any specific questions.

<?php // RAY_image_upload_and_thumbnail.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'RAY_junk';
if (!is_dir($uploads))
{
    mkdir($uploads);
}


// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'png'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>" . PHP_EOL;
    }
    ?>
    <br/>Thumbnail Dimensions:
    <br/>Width <input name="w" />
    <br/>Height <input name="h" />
    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>" . PHP_EOL;

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));

        // USE THIS FOR WRITING ON THE SERVER
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // USE THIS FOR WRITING THE THUMBNAIL ON THE SERVER
        $my_new_tnail
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . 'tn_'
        . $f_name
        . '.png'
        ;

        // USE THIS FOR PREPARING A URL LINK OR CALLING PHP FUNCTIONS
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // USE THIS FOR PREPARING A URL LINK OR CALLING PHP FUNCTIONS
        $my_tnail
        = $uploads
        . DIRECTORY_SEPARATOR
        . 'tn_'
        . $f_name
        . '.png'
        ;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists" . PHP_EOL;;

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>" . PHP_EOL;
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
        // IF NO UPLOAD, DO NOT OVERWRITE ANY EXISTING THUMBNAIL
        else
        {
            die();
        }

        // RESIZE AN IMAGE TO FIT INSIDE A DEFINED TRANSPARENT SPACE
        $image_url = $my_file;

        // ACQUIRE THE DIMENSIONS - MAY NEED SOME SANITY TESTS?
        $thumb_w   = $_POST["w"];
        $thumb_h   = $_POST["h"];

        // CREATE THE THUMBNAIL IMAGE RESOURCE AND FILL IN TRANSPARENT
        $thumb = imageCreateTrueColor($thumb_w, $thumb_h);
        imageSaveAlpha($thumb, TRUE);
        $empty = imageColorAllocateAlpha($thumb,0,0,0,127);
        imageFill($thumb, 0, 0, $empty);

        // GET ORIGINAL IMAGE DIMENSIONS
        $array = getImageSize($my_file);
        if ($array)
        {
            list($image_w, $image_h) = $array;
        }
        else
        {
            die("NO IMAGE $my_file");
        }

        // ACQUIRE THE ORIGINAL IMAGE
        $image_ext = explode('.', $my_file);
        $image_ext = trim(strtoupper(end($image_ext)));
        switch(strtoupper($image_ext))
        {
            case 'JPG' :
            case 'JPEG' :
                $image = imagecreatefromjpeg($image_url);
                break;

            case 'PNG' :
                $image = imagecreatefrompng($image_url);
                break;

            default : die("UNKNOWN IMAGE TYPE: $my_file");
        }

        // GET THE LESSER OF THE RATIO OF THUMBNAIL H OR W DIMENSIONS
        $ratio_w = ($thumb_w / $image_w);
        $ratio_h = ($thumb_h / $image_h);
        $ratio   = ($ratio_w < $ratio_h) ? $ratio_w : $ratio_h;

        // COMPUTE THUMBNAIL IMAGE DIMENSIONS
        $thumb_w_resize = $image_w * $ratio;
        $thumb_h_resize = $image_h * $ratio;

        // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
        $thumb_w_offset = ($thumb_w - $thumb_w_resize) / 2.0;
        $thumb_h_offset = ($thumb_h - $thumb_h_resize) / 2.0;

        // COPY THE IMAGE TO THE CENTER OF THE THUMBNAIL
        imageCopyResampled
        ( $thumb
        , $image
        , $thumb_w_offset
        , $thumb_h_offset
        , 0
        , 0
        , $thumb_w_resize
        , $thumb_h_resize
        , $image_w
        , $image_h
        )
        ;
        // SHARPEN THE THUMBNAIL
		$sharpenMatrix = array
		( array( -1.2, -1, -1.2 )
		, array( -1,   20, -1 )
		, array( -1.2, -1, -1.2 )
		)
		;
		$divisor = array_sum(array_map('array_sum', $sharpenMatrix));
		$offset  = 0;
		imageconvolution($thumb, $sharpenMatrix, $divisor, $offset);

        // (OPTIONAL) SHOW THE NEW THUMB IMAGE DIRECTLY IN BROWSER
        // header('Content-type: image/png');
        // imagePng($thumb);

        // WRITE THE THUMBNAIL TO DISK
        imagePng($thumb, $my_new_tnail);

        // RELEASE THE MEMORY USED BY THE IMAGE RESOURCES
        imageDestroy($thumb);
        imageDestroy($image);

        // CREATE AN IMAGE LINK FOR THE BROWSER
        echo '<br/><a target="_blank" href="' . $my_tnail . '">See the Thumb ' . $my_tnail . '</a>' . PHP_EOL;

    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

And best of luck with your project! ~Ray
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now