Jump to content

Storing Images In Database


morrisjohnny

Recommended Posts

Here's My Code

<?phpinclude"Settings.php";$con=mysql_connect("localhost","root","");mysql_select_db("ASJclothing",$con);if (isset($_POST['completed']))	{		//Safe Data		//Upload File & Data        move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");        $instr = fopen("latest.img","rb");        $image = addslashes(fread($instr,filesize("latest.img")));        if (strlen($instr) < 149000000) {                mysql_query ("INSERT INTO $tbl_products (Ref, Name, img, Price, Type, Description, Size) VALUES ('".(mysql_real_escape_string($_POST['code']))."', '".(mysql_real_escape_string($_POST['name']))."', '".$image."','".(mysql_real_escape_string($_POST['Price']))."','".(mysql_real_escape_string($_POST['Type']))."','".(mysql_real_escape_string($_POST['Desc']))."','".(mysql_real_escape_string($_POST['Size']))."')");        }                $errmsg = "Too large!";}?><html><head><title>Upload an image to a database</title><body><h2>Please upload a new picture and title</h2><form enctype="multipart/form-data" method="post"><input type="hidden" name="MAX_FILE_SIZE" value="150000"><input type="hidden" name="completed" value="1"><table><tr><td>Image:</td><td><input type="file" name="imagefile"></td></tr><tr><td>Product Name:</td><td><input type="text" name="name"></td></tr><tr><td>Product Code:</td><td><input type="text" name="code"></td></tr><tr><td>Product Price:</td><td><input type="text" name="Price"></td></tr><tr><td>Product Type:</td><td><input type="text" name="Type"></td></tr><tr><td>Product Description:</td><td><input type="text" name="Desc"></td></tr><tr><td>Product Size:</td><td><input type="text" name="Size"></td></tr><tr><td colspan="2" align="center"><input type="submit" value="Submit"></td></tr></table></form></body></html>

Now i know the script does update, Problem is the image latest.img doesn't seem to be getting updated. I've tried it on a server and my local host (it used to work on my localhost) But some reasons stopped and i can't work out why? Any suggestions? It's the uploading part i'm having problems with displaying the data is fine.

Link to comment
Share on other sites

You're not doing any error checking or anything like that. Here's a function I wrote to process file uploads, it's come in really handy for me so far. Stick this in an include file somewhere so that it's defined:

function handle_file_upload($options){  $input = !empty($options['input']) ? $options['input'] : trigger_error('handle_file_upload: No input name specified', E_USER_ERROR);  $dest = !empty($options['dest_dir']) ? $options['dest_dir'] : trigger_error('handle_file_upload: No destination name specified', E_USER_ERROR);  $dest_fname = !empty($options['dest_fname']) ? $options['dest_fname'] : '';  $overwrite = !empty($options['overwrite']) ? $options['overwrite'] : false;  $mode = !empty($options['mode']) ? $options['mode'] : false;  $allowed_ext = isset($options['allowed_ext']) && is_array($options['allowed_ext']) ? $options['allowed_ext'] : false;  if (!is_dir($dest))    trigger_error('handle_file_upload: Destination directory does not exist', E_USER_ERROR);  if (!isset($_FILES[$input]))    trigger_error('handle_file_upload: The input file was not found', E_USER_ERROR);  if ($_FILES[$input]['error'] > 0)  {    switch ($_FILES[$input]['error'])    {      case 1:      case 2; return array('success' => false, 'error' => 'The uploaded file was too large.');      case 3: return array('success' => false, 'error' => 'The uploaded file was only partially received.');      case 4: return array('success' => false, 'error' => 'No file was uploaded.');      case 6: return array('success' => false, 'error' => 'Missing temporary folder.');      case 7: return array('success' => false, 'error' => 'Failed to write file to disk.');      case 8: return array('success' => false, 'error' => 'Invalid extension.');    }  }    if ($allowed_ext != false && !in_array(strtolower(array_pop(explode('.', $_FILES[$input]['name']))), $allowed_ext))    return array('success' => false, 'error' => 'That file type was not allowed.');  if ($dest_fname != '')    $_FILES[$input]['name'] = $dest_fname;  $_FILES[$input]['name'] = strtolower(basename($_FILES[$input]['name']));  if (!$overwrite)  {    $fname = $_FILES[$input]['name'];    if (file_exists($dest . DIRECTORY_SEPARATOR . $fname))    {      $chunks = explode('.', $fname);      $ext = array_pop($chunks);      $fname = implode('.', $chunks);      $nr = 1;      while (file_exists($dest . DIRECTORY_SEPARATOR . $fname . '.' . $ext))        $fname = $fname . '.' . $nr++;      $_FILES[$input]['name'] = $fname . '.' . $ext;    }  }  $target = $dest . DIRECTORY_SEPARATOR . $_FILES[$input]['name'];  if (!move_uploaded_file($_FILES[$input]['tmp_name'], $target))    return array('success' => false, 'error' => 'The uploaded file could not be moved.');  if ($mode !== false)    chmod($target, $mode);  return array('success' => true, 'name' => $_FILES[$input]['name']);}

The input to that function is an array with all the options. I used an array because there are several optional options (?) and it's easier to use an array instead of remember which order and which are optional. The required options are the input name and the destination directory. Your code might be having problems because you're not giving the destination a directory, only a filename. The other options are a filename to use for the new file, an overwrite flag to tell it to either overwrite an existing file or rename the new one to avoid overwriting, a permission mode to set the file to after copying it, and an array of extensions to allow. It will return an array with a few things in it. It will have a "success" property indicating if the upload succeeded or not, and if not, it will have an "error" property with the error message. It may also trigger a fatal error if the inputs are wrong. If the upload succeeded, the return array will have a "name" property with the file name (in case it was renamed to avoid overwriting). Your PHP code to use this might look like this:

<?phpinclude"Settings.php";$con=mysql_connect("localhost","root","");mysql_select_db("ASJclothing",$con);if (isset($_POST['completed'])){  //move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");  $file = handle_file_upload(array(	'input' => 'imagefile',	'dest_dir' => dirname(__FILE__),  // to upload to the current directory	'dest_fname' => 'latest.img', // optional	'overwrite' => true, // optional	'mode' => 0664, // optional	'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional  ));  if (!$file['success'])  {	$errmsg = $file['error'];  }  else  {	$instr = fopen($file['name'],"rb");	$image = addslashes(fread($instr,filesize($file['name'])));	if (strlen($instr) < 149000000) {	  mysql_query ("INSERT INTO $tbl_products (Ref, Name, img, Price, Type, Description, Size) VALUES ('".(mysql_real_escape_string($_POST['code']))."', '".(mysql_real_escape_string($_POST['name']))."', '".$image."','".(mysql_real_escape_string($_POST['Price']))."','".(mysql_real_escape_string($_POST['Type']))."','".(mysql_real_escape_string($_POST['Desc']))."','".(mysql_real_escape_string($_POST['Size']))."')");	}	else	  $errmsg = "Too large!";  }}?>

Link to comment
Share on other sites

  • 2 weeks later...

Thanks JustSomeGuy, However it still doesn't work. It doesn't display any error message and the image still isn't being uploaded. maybe i'm implementing it wrong?If it's any help i'm now trying to insert the pictures into another database called images with the fields: ID, img. (ID just being an increasement and img being the uploaded image). if you could help out i'd be very greatful as it's the only part missing in both my final two portfolio

Link to comment
Share on other sites

The basic concept of that function is pretty easy, you just give it the information that applies to the file upload and it will return an array that indicates if it failed or succeeded and either an error message or the saved filename.

  $file = handle_file_upload(array(	'input' => 'imagefile',	'dest_dir' => dirname(__FILE__),  // to upload to the current directory	'dest_fname' => 'latest.img', // optional	'overwrite' => true, // optional	'mode' => 0664, // optional	'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional  ));  if (!$file['success'])  {	$errmsg = $file['error'];  }  else  {	echo 'file saved as ' . $file['name'];  }

If you want help with something specific, post the code you're using. And make sure error messages are either being displayed or logged, there are several error conditions where this function just fails with an error message instead of returning an array.

Link to comment
Share on other sites

  • 1 month later...

Thanks JustSomeGuyI've now got the code working perfectly, However is their a way i can resize the image. I don't want to just use html to change the width and height as it will still be storing large images within the database for no reason. However if it's easier we could crop a section out of the picture (prefereably the middle but top corners are good too) and use that.?Any suggestions i've tried looking online but they only load the image and then save it with another file name and not using databases.

Link to comment
Share on other sites

Here's a function to resize an image:

function resize_image($opts){  $src = isset($opts['source']) ? $opts['source'] : '';  $dest = isset($opts['dest']) ? $opts['dest'] : '';  $w = isset($opts['w']) ? intval($opts['w']) : 0;  $h = isset($opts['h']) ? intval($opts['h']) : 0;  if ($src == '')  {    return false;  }  if ($w == 0 && $h == 0)  {    return false;  }  if ($dest == '')    $dest = $src; // resize in place  // open the image  $ext = strtolower(array_pop(explode('.', $src)));  switch ($ext)  {    case 'jpg':    case 'jpeg':      $i = imagecreatefromjpeg($src);    break;    case 'gif':      $i = imagecreatefromgif($src);    break;    case 'png':      $i = imagecreatefrompng($src);    break;    default:      return false;  }  $new_w = imagesx($i);  $new_h = imagesy($i);  if (($w != 0 && $new_w < $w && $h == 0) ||      ($w == 0 && $h != 0 && $new_h < $h) ||      ($w != 0 && $new_w < $w && $h != 0 && $new_h < $h))  {    // image is small enough    if ($dest != $src)    {      copy($src, $dest);      chmod($dest, 0644);    }    return true;  }  // determine new size  if ($w != 0 && $new_w > $w)  {    $new_h = ($w / $new_w) * $new_h;    $new_w = $w;  }  if ($h != 0 && $new_h > $h)  {    $new_w = ($h / $new_h) * $new_w;    $new_h = $h;  }  // resize  $new = imagecreatetruecolor($new_w, $new_h);  imagecopyresampled($new, $i, 0, 0, 0, 0, $new_w, $new_h, imagesx($i), imagesy($i));  imagedestroy($i);  // save the image  switch ($ext)  {    case 'jpg':    case 'jpeg':      imagejpeg($new, $dest);    break;    case 'gif':      imagegif($new, $dest);    break;    case 'png':      imagepng($new, $dest);    break;  }    chmod($dest, 0644);  imagedestroy($new);  return true;}

ex:

  $file = handle_file_upload(array(	'input' => 'imagefile',	'dest_dir' => dirname(__FILE__),  // to upload to the current directory	'dest_fname' => 'latest.img', // optional	'overwrite' => true, // optional	'mode' => 0664, // optional	'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional  ));  if (!$file['success'])  {	$errmsg = $file['error'];  }  else  {	echo 'file saved as ' . $file['name'];	$success = resize_image(array(	  'source' => $file['name'], // image to resize	  'w' => 500, // max width	  'h' => 500 // max height	));  }

You can also send the function a 'dest' option that will give a new filename to save it as, or else it will save over the original. It will resize in proportion and only resize down, if the width and height are greater than the image it won't do anything. Or else it will resize the image down until it fits within the width and height. The width and height are both optional, but you need to send at least one.

Link to comment
Share on other sites

Right, here's the code I'm currently using, how would i implement the the scaling down of the image within this? I'm wanting to just call $image when i went to enter it in the database, I've only complete the new sweet area and not editing of sweets and neither of the links. but that should be similar

<?phpsession_start();$logged_in = false;$msg = "";if ($_SESSION['online'])  $logged_in = true;else if (isset($_POST['ytrewq'])){  $user=$_POST['ytrewq'];  $pass=$_POST['qwerty'];	if ($user=="sweetmemories" && $pass=="sweeties")		{		$_SESSION['online'] = true;		$logged_in = true;		}}if($logged_in){//LOGGED INinclude"__connect__.php";if(isset($_POST['imagefile'])){function handle_file_upload($options){$input = !empty($options['input']) ? $options['input'] : trigger_error('handle_file_upload: No input name specified', E_USER_ERROR);$dest = !empty($options['dest_dir']) ? $options['dest_dir'] : trigger_error('handle_file_upload: No destination name specified', E_USER_ERROR);$dest_fname = !empty($options['dest_fname']) ? $options['dest_fname'] : '';$overwrite = !empty($options['overwrite']) ? $options['overwrite'] : false;$mode = !empty($options['mode']) ? $options['mode'] : false;$allowed_ext = isset($options['allowed_ext']) && is_array($options['allowed_ext']) ? $options['allowed_ext'] : false;if (!is_dir($dest))trigger_error('handle_file_upload: Destination directory does not exist', E_USER_ERROR);if (!isset($_FILES[$input]))trigger_error('handle_file_upload: The input file was not found', E_USER_ERROR);	if ($_FILES[$input]['error'] > 0)	{	switch ($_FILES[$input]['error'])	{	case 1:	case 2; return array('success' => false, 'error' => 'The uploaded file was too large.');	case 3: return array('success' => false, 'error' => 'The uploaded file was only partially received.');	case 4: return array('success' => false, 'error' => 'No file was uploaded.');	case 6: return array('success' => false, 'error' => 'Missing temporary folder.');	case 7: return array('success' => false, 'error' => 'Failed to write file to disk.');	case 8: return array('success' => false, 'error' => 'Invalid extension.');	}}if ($allowed_ext != false && !in_array(strtolower(array_pop(explode('.', $_FILES[$input]['name']))), $allowed_ext))return array('success' => false, 'error' => 'That file type was not allowed.');if ($dest_fname != '')$_FILES[$input]['name'] = $dest_fname;$_FILES[$input]['name'] = strtolower(basename($_FILES[$input]['name']));if (!$overwrite){$fname = $_FILES[$input]['name'];if (file_exists($dest . DIRECTORY_SEPARATOR . $fname)){$chunks = explode('.', $fname);$ext = array_pop($chunks);$fname = implode('.', $chunks);$nr = 1;while (file_exists($dest . DIRECTORY_SEPARATOR . $fname . '.' . $ext))$fname = $fname . '.' . $nr++;$_FILES[$input]['name'] = $fname . '.' . $ext;}}$target = $dest . DIRECTORY_SEPARATOR . $_FILES[$input]['name'];if (!move_uploaded_file($_FILES[$input]['tmp_name'], $target))return array('success' => false, 'error' => 'The uploaded file could not be moved.');if ($mode !== false)chmod($target, $mode);return array('success' => true, 'name' => $_FILES[$input]['name']);}/////////////////////////////////////////////////////////////////////////////if (isset($_POST['completed'])){  //move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");  $file = handle_file_upload(array(	'input' => 'imagefile',	'dest_dir' => dirname(__FILE__),  // to upload to the current directory	'dest_fname' => 'latest.img', // optional	'overwrite' => true, // optional	'mode' => 0664, // optional	'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional  ));  if (!$file['success'])  {	$errmsg = $file['error'];  }  else  {	$instr = fopen($file['name'],"rb");	$image = addslashes(fread($instr,filesize($file['name'])));		echo mysql_error().'<br /></br ><strong>';	  mysql_query("INSERT INTO $tbl_images (img) VALUES('".$image."')");	  echo mysql_error().'</strong>';	  echo $image;  }}}?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><link href="style.css" rel="stylesheet" type="text/css" /><!-- MUM Here's your meta's !--><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><META name="author" content="Jonathon Morris"><META name="publisher" content="Sweet Memories Online"><META name="copyright" content="Sweet Memories Online"><META name="page-topic" content="Business"><META name="page-type" content="Online Store With Old Sweets"><meta name="description" content="Sweet Memories Online is an old fashioned sweet shop which sells some of the most popular old sweets which are still made such as Sweet Tobacco, Liquorice Comfits, Sports Mixtures and North East Regional Sweets, Berwick Cockles, Black Bullets." /><meta name="keywords" content="Old Trandidtional, Sweet Shop, Retro, Sweets, Quater of, Berwick, TD15, North East, England, Uk" /><!-- End Of meta's !--><title>Welcome To Sweet Memories Online</title></head><body><div style="width:900px;margin-left:auto;margin-right:auto;"><!-- Keep Left!--><div class="keepleft" style="float:left;width:149px;">	<div class="overlay" style="float:left">	<div class="header"><strong>Menu</strong></div>	<div class="context">			<div onclick="document.location='';">Home / Stats</div>		<div onclick="document.location='?view=new_sweet';">New Sweet</div>		<div onclick="document.location='?view=edit_sweet';">Edit Sweet</div>		<div onclick="document.location='?view=new_link';">New Link</div>		<div onclick="document.location='?view=edit_link';">Edit Link</div>		</div>	</div></div><!-- End Keep Left !--><!-- Keep Right !--><div class="keepright" style="float:right;width:745px;"><!-- TemplateBeginEditable name="main_page" -->	<?phpif(isset($_GET['view'])){	if($_GET['view']=="new_sweet")	{		if(isset($_POST['name']))		{			$new_sweet="INSERT INTO $tbl_products (name, img, type, price, unit, ingred, description) VALUES ('".(mysql_real_escape_string($_POST['name']))."', '".$image."', '".(mysql_real_escape_string($_POST['type']))."', '".(mysql_real_escape_string($_POST['price']))."', '".(mysql_real_escape_string($_POST['unit']))."', '".(mysql_real_escape_string($_POST['ingred']))."', '".(mysql_real_escape_string($_POST['description']))."')";			if(mysql_query($new_sweet))			{				$new_sweet_msg='Sweet Succesfully Added';			} else {$new_sweet_msg='Sweet Failed to be added'.mysql_error();}		}		echo'<div class="overlay" style="float:right">		<div class="header">Sweet Memories New Sweet</div>		<div class="context" style="text-align:center;">';if(isset($new_sweet_msg)){echo $new_sweet_msg;}echo'		<form action="" enctype="multipart/form-data" method="post"><input type="hidden" name="MAX_FILE_SIZE" value="150000000000000000000000">		<input type="hidden" name="completed" value="1">		<table style="width:500px;border:#000000 thin solid;margin-left:auto;margin-right:auto;">		<tr><td>Sweet Name:</td><td><input type="text" name="name" style="width:100%;" /></td></tr>		<tr><td>Sweet Image:</td><td><input type="file" name="imagefile" style="width:100%;"></td></tr>		<tr><td>Sweet Type:</td><td><input type="text" name="type" style="width:100%;" /></td></tr>		<tr><td>Sweet Price:</td><td><input type="text" name="price" style="width:100%;" /></td></tr>		<tr><td>Sweet Unit:</td><td><select style="width:100%;" name="unit"><option selected="selected" value="Per 100 grams">Per 100 grams</option><option value="Per One">Per One</option></select></td></tr>		<tr><td>ingredients</td><td><textarea rows="5" style="width:100%;" name="ingred"></textarea></td></tr>		<tr><td>Description</td><td><textarea rows="5" style="width:100%;" name="description"></textarea></td></tr>		<tr><td colspan="2" style="text-align:center;"><input type="submit" value="Add New Sweet" /></td></tr>		</table></form>		</div>	</div>';	}	else if($_GET['view']=="edit_sweet")	{		if(isset($_GET['type']))		{			if(isset($_GET['id']))			{				$gtype=mysql_query("SELECT * FROM $tbl_products WHERE id='".mysql_real_escape_string($_GET['id'])."'");				$stype=mysql_fetch_array($gtype);				if(isset($_POST['name']))				{					//INSERT EDIT SWEET SCRIPT				}				echo'<div class="overlay" style="float:right">				<div class="header">Sweet Memories - Edit Sweet</div>				<div class="context" style="text-align:center;">				<form action="" method="post"><input type="hidden" name="MAX_FILE_SIZE" value="150000000000000000000000">			<input type="hidden" name="completed" value="1">			<table style="width:500px;border:#000000 thin solid;margin-left:auto;margin-right:auto;">			<tr><td>Sweet Name:</td><td><input type="text" name="name" value="'.$stype["name"].'" style="width:100%;" /></td></tr>			<tr><td>Sweet Image:</td><td><input type="file" name="imagefile" style="width:100%;"></td></tr>			<tr><td>Sweet Type:</td><td><input type="text" name="type" value="'.$stype["type"].'" style="width:100%;" /></td></tr>			<tr><td>Sweet Price:</td><td><input type="text" name="price" value="'.$stype["price"].'" style="width:100%;" /></td></tr>			<tr><td>Sweet Unit:</td><td><select style="width:100%;" name="unit"><option selected="selected" value="Per 100 grams">Per 100 grams</option><option value="Per One">Per One</option></select></td></tr>			<tr><td>ingredients</td><td><textarea rows="5" style="width:100%;" name="ingred">'.$stype["ingred"].'</textarea></td></tr>			<tr><td>Description</td><td><textarea rows="5" style="width:100%;" name="description">'.$stype["description"].'</textarea></td></tr>			<tr><td colspan="2" style="text-align:center;"><input type="submit" value="Add New Sweet" /></td></tr>			</table></form>				</div>				</div>';			}			else			{			echo'<div class="overlay" style="float:right">			<div class="header">Sweet Memories - Edit Sweet (Select Sweet)</div>			<div class="context" style="text-align:center;">';			$gtype=mysql_query("SELECT * FROM $tbl_products WHERE type='".mysql_real_escape_string($_GET['type'])."'");			while($stype=mysql_fetch_array($gtype))			{				echo'<div style="margin-top:5px;"><a href="?view=edit_sweet&type='.$stype["type"].'&id='.$stype["id"].'">'.$stype["name"].'</a></div>';			}			echo'</div></div>';			}		}		else		{		echo'<div class="overlay" style="float:right">		<div class="header">Sweet Memories - New Link</div>		<div class="context" style="text-align:center;">';		$gtype=mysql_query("SELECT * FROM $tbl_products GROUP BY type");		while($stype=mysql_fetch_array($gtype))		{			echo'<div style="margin-top:5px;"><a href="?view=edit_sweet&type='.$stype["type"].'">'.$stype["type"].'</a></div>';		}		echo'</div></div>';		}	}	else if($_GET['view']=="new_link")	{		if(isset($_POST['name']))		{			//INSERT EDIT SWEET SCRIPT		}		echo'<div class="overlay" style="float:right">		<div class="header">Sweet Memories - New Link</div>		<div class="context" style="text-align:center;">		<form action="" method="post"><input type="hidden" name="MAX_FILE_SIZE" value="150000000000000000000000">		<input type="hidden" name="completed" value="1">		<table style="width:500px;border:#000000 thin solid;margin-left:auto;margin-right:auto;">		<tr><td>Link Name:</td><td><input type="text" name="name" style="width:100%;" /></td></tr>		<tr><td>Link Image:</td><td><input type="file" name="imagefile" style="width:100%;"></td></tr>		<tr><td>Link Address: (including http://www.)</td><td><input type="text" name="address" style="width:100%;" /></td></tr>		<tr><td>Description</td><td><textarea rows="5" style="width:100%;" name="description"></textarea></td></tr>		<tr><td colspan="2" style="text-align:center;"><input type="submit" value="Add New Link" /></td></tr>		</table></form>		</div>	</div>';	}	else if($_GET['view']=="edit_link")	{		if(isset($_GET['id']))		{			$gtype=mysql_query("SELECT * FROM $tbl_links");			$stype=mysql_fetch_array($gtype);			if(isset($_POST['name']))			{				//INSERT EDIT SWEET SCRIPT			}			echo'<div class="overlay" style="float:right">			<div class="header">Sweet Memories - New Link</div>			<div class="context" style="text-align:center;">			<form action="" method="post"><input type="hidden" name="MAX_FILE_SIZE" value="150000000000000000000000">			<input type="hidden" name="completed" value="1">			<table style="width:500px;border:#000000 thin solid;margin-left:auto;margin-right:auto;">			<tr><td>Link Name:</td><td><input type="text" name="name" value="'.$stype["name"].'" style="width:100%;" /></td></tr>			<tr><td>Link Image:</td><td><input type="file" name="imagefile" style="width:100%;"></td></tr>			<tr><td>Link Address: (including http://www.)</td><td><input type="text" name="address" value="'.$stype["address"].'" style="width:100%;" /></td></tr>			<tr><td>Description</td><td><textarea rows="5" style="width:100%;" name="description">'.$stype["description"].'</textarea></td></tr>			<tr><td colspan="2" style="text-align:center;"><input type="submit" value="Add New Link" /></td></tr>			</table></form>			</div>		</div>';		}		else		{		echo'<div class="overlay" style="float:right">		<div class="header">Sweet Memories - Edit Link</div>		<div class="context" style="text-align:center;">';		$gtype=mysql_query("SELECT * FROM $tbl_links");		while($stype=mysql_fetch_array($gtype))		{			echo'<div style="margin-top:5px;"><a href="?view=edit_link&id='.$stype["id"].'">'.$stype["name"].'</a></div>';		}		echo'</div></div>';		}	}	else	{		echo'<div class="overlay" style="float:right">		<div class="header">Sweet Memories Online Statistics</div>		<div class="context" style="text-align:center;">Sorry, This page doesn\' exist. If you followed a link please report this link to <a href="mailto:jnymris@hotmail.co.uk">jnymris@hotmail.co.uk</a>.</div>	</div>';	}} else { ?>		<div class="overlay" style="float:right">		<div class="header">Sweet Memories Online Statistics</div>		<div class="context" style="text-align:center;"><iframe src="http://www.sweetmemoriesonline.co.uk/webstats/" style="width:100%;height:500px;"></iframe></div></div></div><?php } ?><!-- TemplateEndEditable --><!-- End Keep Right !--><div style="margin-top:10px;float:right;width:100%;text-align:center;background-color:#FFFFCC;"><a href="mailto:fastb01@gmail.com" style="color:#993300">Designed By Johnny Morris</a></div></div></body></html><?php}else{echo'<form action="" method="post"><input type="text" name="qwerty" /><input type="text" name="ytrewq" /><input type="submit" /></form>';}?>

Link to comment
Share on other sites

You can just call the resize_image function before getting the data to save in the database.

	$success = resize_image(array(	  'source' => $file['name'], // image to resize	  'w' => 500, // max width	  'h' => 500 // max height	));

Also, it will clean the code up if you move the function definitions into an include file.

Link to comment
Share on other sites

i included the function to rezise the image ABOVE the other function and then included

   $success = resize_image(array(	  'source' => $file['name'], // image to resize	  'w' => 500, // max width	  'h' => 500 // max height	));

after

  {	$instr = fopen($file['name'],"rb");	$image = addslashes(fread($instr,filesize($file['name'])));

and the image seems to be lost as theirs no image and in the database it says [bLOB - 0 B] which implies it's empty

Link to comment
Share on other sites

First, you would want to resize before you read the data, not after. The $file['name'] value will only contain the filename, not the path. Make sure you give it the full path of the file to open. Also, find something to do with the error message after uploading the file, there might be something there. Verify that the file is actually getting uploaded.

Link to comment
Share on other sites

First, you would want to resize before you read the data, not after. The $file['name'] value will only contain the filename, not the path. Make sure you give it the full path of the file to open. Also, find something to do with the error message after uploading the file, there might be something there. Verify that the file is actually getting uploaded.
so where should i be putting the data? the $file['name'] works so far as all the files are in the one folder just to make it easier, i was going to convert all the image data into another file and include it once i got it all working and then jsut call $image when needed.
Link to comment
Share on other sites

so putting

  $success = resize_image(array(	  'source' => $file['name'], // image to resize	  'w' => 500, // max width	  'h' => 500 // max height	));

After

if (isset($_POST['completed'])){

and before

//move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");  $file = handle_file_upload(array(	'input' => 'imagefile',	'dest_dir' => dirname(__FILE__),  // to upload to the current directory	'dest_fname' => 'latest.img', // optional	'overwrite' => true, // optional	'mode' => 0664, // optional	'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional  ));  if (!$file['success'])  {	$errmsg = $file['error'];  }  else  {	$instr = fopen($file['name'],"rb");	$image = addslashes(fread($instr,filesize($file['name'])));		echo mysql_error().'<br /></br ><strong>';	  mysql_query("INSERT INTO $tbl_images (img) VALUES('".$image."')");	  echo mysql_error().'</strong>';	  echo $image;  }}}

Should make it work right?

Link to comment
Share on other sites

  • 3 weeks later...

Thanks i managed to do this, However i'm now wondering if their is a way to upload two images from the same form? i've tried

require"image_function.php";if (isset($_POST['completed'])){		  //move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");		  $file = handle_file_upload(array(		    'input' => 'imagefile',		    'dest_dir' => dirname(__FILE__),  // to upload to the current directory		    'dest_fname' => 'latest.img', // optional		    'overwrite' => true, // optional		    'mode' => 0664, // optional		    'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional		  ));		  if (!$file['success'])		  {		    $errmsg = $file['error'];		  }		  else		  {		    $instr = fopen($file['name'],"rb");	    $success = resize_image(array(	      'source' => $file['name'], // image to resize	      'w' => 500, // max width	      'h' => 500 // max height		   )			);}		  $file2 = handle_file_upload(array(		    'input' => 'imagefile2',		    'dest_dir' => dirname(__FILE__),  // to upload to the current directory		    'dest_fname' => 'latest2.img', // optional		    'overwrite' => true, // optional		    'mode' => 0664, // optional		    'allowed_ext' => array('jpg', 'jpeg', 'gif', 'png') // optional		  ));		  if (!$file['success'])		  {		    $errmsg = $file['error'];		  }		  else		  {		    $instr2 = fopen($file2['name'],"rb");	    $success = resize_image(array(	      'source' => $file['name'], // image to resize	      'w' => 500, // max width	      'h' => 500 // max height		   )			);}$image=addslashes(fread($instr,filesize($file['name'])));$image2=addslashes(fread($instr2,filesize($file2['name'])));$query="INSERT INTO images (img) VALUES ('$image')";$query2="INSERT INTO images (img) VALUES ('$image2')";if(!mysql_query($query)){echo mysql_error();}else{echo "DONE";}if(!mysql_query($query2)){echo mysql_error();}else{echo "DONE";}}		   ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><link href="style.css" rel="stylesheet" type="text/css" /><meta name="author" content="Jonathon Morris" /><meta name="robots" content="noindex" /><meta name="robots" content="nofollow" /><title>Red Dragon Stores</title></head><body><form action="" enctype="multipart/form-data" method="post"><input type="hidden" name="MAX_FILE_SIZE" value="150000000000000000000000"><input type="hidden" name="completed" value="1"><input type="file" name="imagefile" style="width:100%;"><input type="file" name="imagefile2" style="width:100%;"><input type="submit" value="Submit" /></form><table><tr><td></td></tr></table></body></html>

and the image_function.php

<?php//functionsfunction resize_image($opts){$src = isset($opts['source']) ? $opts['source'] : '';$dest = isset($opts['dest']) ? $opts['dest'] : '';$w = isset($opts['w']) ? intval($opts['w']) : 0;$h = isset($opts['h']) ? intval($opts['h']) : 0;if ($src == ''){return false;}if ($w == 0 && $h == 0){return false;}if ($dest == '')$dest = $src; // resize in place// open the image$ext = strtolower(array_pop(explode('.', $src)));switch ($ext){case 'jpg':case 'jpeg':$i = imagecreatefromjpeg($src);break;case 'gif':$i = imagecreatefromgif($src);break;case 'png':$i = imagecreatefrompng($src);break;default:return false;}$new_w = imagesx($i);$new_h = imagesy($i);if (($w != 0 && $new_w < $w && $h == 0) ||($w == 0 && $h != 0 && $new_h < $h) ||($w != 0 && $new_w < $w && $h != 0 && $new_h < $h)){// image is small enoughif ($dest != $src){copy($src, $dest);chmod($dest, 0644);}return true;}// determine new sizeif ($w != 0 && $new_w > $w){$new_h = ($w / $new_w) * $new_h;$new_w = $w;}if ($h != 0 && $new_h > $h){$new_w = ($h / $new_h) * $new_w;$new_h = $h;}// resize$new = imagecreatetruecolor($new_w, $new_h);imagecopyresampled($new, $i, 0, 0, 0, 0, $new_w, $new_h, imagesx($i), imagesy($i));imagedestroy($i);// save the imageswitch ($ext){case 'jpg':case 'jpeg':imagejpeg($new, $dest);break;case 'gif':imagegif($new, $dest);break;case 'png':imagepng($new, $dest);break;}chmod($dest, 0644);imagedestroy($new);return true;}//Start Final Functionfunction handle_file_upload($options){$input = !empty($options['input']) ? $options['input'] : trigger_error('handle_file_upload: No input name specified', E_USER_ERROR);$dest = !empty($options['dest_dir']) ? $options['dest_dir'] : trigger_error('handle_file_upload: No destination name specified', E_USER_ERROR);$dest_fname = !empty($options['dest_fname']) ? $options['dest_fname'] : '';$overwrite = !empty($options['overwrite']) ? $options['overwrite'] : false;$mode = !empty($options['mode']) ? $options['mode'] : false;$allowed_ext = isset($options['allowed_ext']) && is_array($options['allowed_ext']) ? $options['allowed_ext'] : false;if (!is_dir($dest))trigger_error('handle_file_upload: Destination directory does not exist', E_USER_ERROR);if (!isset($_FILES[$input]))trigger_error('handle_file_upload: The input file was not found', E_USER_ERROR);	if ($_FILES[$input]['error'] > 0)	{	switch ($_FILES[$input]['error'])	{	case 1:	case 2; return array('success' => false, 'error' => 'The uploaded file was too large.');	case 3: return array('success' => false, 'error' => 'The uploaded file was only partially received.');	case 4: return array('success' => false, 'error' => 'No file was uploaded.');	case 6: return array('success' => false, 'error' => 'Missing temporary folder.');	case 7: return array('success' => false, 'error' => 'Failed to write file to disk.');	case 8: return array('success' => false, 'error' => 'Invalid extension.');	}}if ($allowed_ext != false && !in_array(strtolower(array_pop(explode('.', $_FILES[$input]['name']))), $allowed_ext))return array('success' => false, 'error' => 'That file type was not allowed.');if ($dest_fname != '')$_FILES[$input]['name'] = $dest_fname;$_FILES[$input]['name'] = strtolower(basename($_FILES[$input]['name']));if (!$overwrite){$fname = $_FILES[$input]['name'];if (file_exists($dest . DIRECTORY_SEPARATOR . $fname)){$chunks = explode('.', $fname);$ext = array_pop($chunks);$fname = implode('.', $chunks);$nr = 1;while (file_exists($dest . DIRECTORY_SEPARATOR . $fname . '.' . $ext))$fname = $fname . '.' . $nr++;$_FILES[$input]['name'] = $fname . '.' . $ext;}}$target = $dest . DIRECTORY_SEPARATOR . $_FILES[$input]['name'];if (!move_uploaded_file($_FILES[$input]['tmp_name'], $target))return array('success' => false, 'error' => 'The uploaded file could not be moved.');if ($mode !== false)chmod($target, $mode);return array('success' => true, 'name' => $_FILES[$input]['name']);}//end functions?>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...