Storing and displaying the image stored as varbinary in MSSQL server using PHP (CodeIgniter)

I am not used to MSSql server with php . MSSQL server has very less documentation compared to Mysql . So here I am writing a short snippets to upload image to MSSQL server in field type ‘varbinary’ and display the image to browser using php framework codeIgniter. Using framework for php application development is always a good idea.

Here is a php snippet to store the uploaded image in the MSSQL server ( datatype = varbinay(MAX)) .

function do_upload()
	{
		$config['upload_path'] = './uploads/';
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '100';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
 
		$this->load->library('upload', $config);
 
		if ( ! $this->upload->do_upload())
		{
			$error = array('error' => $this->upload->display_errors());
 
			$this->load->view('upload_form', $error);
		}	
		else
		{
			$data = $this->upload->data(); 
 
 
                        $dataString = file_get_contents($data['full_path']);
                        $arrData = unpack("H*hex", $dataString);
                        $data_string = "0x".$arrData['hex'];
                        // now we can insert the $data_string variable into the sql server using it respective sql query.
			delete_files($data['full_path']) // we don't want the image to be stored in the web server. 
                        //$this->load->view('upload_success', $data);
		}
	}

Now its little tricky to render the image in the browser that is stored in the MSSQL server ,varbinary(MAX) datatype.

<img src="<?=$this->config->item('BASEURL');?>display_image/convert_image/$row->id?> width="74" height="53" />
 
// baseurl returns the base_url().'index.php/'  (my custom config) 
// display_image is controller name  
// convert_image is method name 
//$row->id returns the primary key of that particular image row.It is used for query to the database.

Now here is my controller to render image on the browser .

<? if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
class Display_Image extends Controller
{ 
	function Display_Image() 
	{ 
		parent::Controller(); 
	} 
	function convert_image()
	{ 
 
		$row =  $this->my_model->get_row($this->uri->segment(3));// to get the image data from the database where my_model is model to fetch the row. 
                $image_data = $row->image; 
		header("Content-Type: image/jpeg");// to tell browser that content type is jpeg image.  
		print $image_data; 
 
	} 
 
} 
?>

This is how we can store and display image using MSSQL server in datatype varbinary (MAX).
I hope this information is helpful who are having hard time to find the solution .

1,507 views
CodeIgniter, MSSQL Server, Php

Leave Comment

(required)

(required)