7 Replies - 7281 Views - Last Post: 06 December 2010 - 04:47 PM Rate Topic: -----

#1 ninethousandfeet@msn.com  Icon User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 310
  • Joined: 09-February 09

Upload image file to Directory, and image name to db

Post icon  Posted 24 March 2009 - 10:49 PM

hello,

can someone please take a look at this code and let me know where i've gone wrong? i'm going in circles and getting the same results. currently, my postTable has a field for an optional image addition. the field is image_data (blob). with my code now, if a pic is added, i receive NO image/file on my directory, i only receive an entry into my db... the field populates with the file name(eg. picone.gif... stored as BLOB - 10B.
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 51200);
if (isset($_FILES['image_data'])) {
// define constant for upload folder
define('UPLOAD_DIR', '/domains/mysite.com/public_html/upload');
// replace any spaces in original filename with underscores
// at the same time, assign to a simpler variable
$file = str_replace(' ', '_', $_FILES['image_data']);
// convert the maximum size to KB
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
// create an array of permitted MIME types
$permitted = array('image_data/gif', 'image_data/jpeg', 'image_data/pjpeg', 'image_data/png');
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;

// check that file is within the permitted size
if ($_FILES['image_data']['size'] > 0 && $_FILES['image_data']['size'] <= MAX_FILE_SIZE) {
$sizeOK = true;
}

// check that file is of a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image_data']['type']) {
$typeOK = true;
break;
}
}

if ($sizeOK && $typeOK) {
$success = move_uploaded_file($_FILES['image_data']['tmp_name'], UPLOAD_DIR.'/'.$file);
}

  $insertSQL = sprintf("INSERT INTO postingTable (post_id, post_title, product_name, user_id, post_date, buy_or_share, category_name, image_data) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
					   GetSQLValueString($_POST['post_id'], "int"),
					   GetSQLValueString($_POST['post_title'], "text"),
					   GetSQLValueString($_POST['product_name'], "text"),
					   GetSQLValueString($_POST['user_id'], "int"),
					   GetSQLValueString($_POST['post_date'], "defined", 'NOW()'),
					   GetSQLValueString($_POST['buy_or_share'], "text"),
					   GetSQLValueString($_POST['category_name'], "text"),
					   GetSQLValueString($_FILES['image_data'], "text"));
  mysql_select_db($database_connUser, $connUser);
  $Result1 = mysql_query($insertSQL, $connUser) or die(mysql_error());

  $insertGoTo = "userprofile.php";
  if (isset($_SERVER['QUERY_STRING'])) {
	$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
	$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Upload image file to Directory, and image name to db

#2 Gevie  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 29
  • Joined: 06-April 08

Re: Upload image file to Directory, and image name to db

Posted 28 March 2009 - 03:45 PM

View Postninethousandfeet@msn.com, on 24 Mar, 2009 - 09:49 PM, said:

hello,

can someone please take a look at this code and let me know where i've gone wrong? i'm going in circles and getting the same results. currently, my postTable has a field for an optional image addition. the field is image_data (blob). with my code now, if a pic is added, i receive NO image/file on my directory, i only receive an entry into my db... the field populates with the file name(eg. picone.gif... stored as BLOB - 10B.
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 51200);
if (isset($_FILES['image_data'])) {
// define constant for upload folder
define('UPLOAD_DIR', '/domains/mysite.com/public_html/upload');
// replace any spaces in original filename with underscores
// at the same time, assign to a simpler variable
$file = str_replace(' ', '_', $_FILES['image_data']);
// convert the maximum size to KB
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
// create an array of permitted MIME types
$permitted = array('image_data/gif', 'image_data/jpeg', 'image_data/pjpeg', 'image_data/png');
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;

// check that file is within the permitted size
if ($_FILES['image_data']['size'] > 0 && $_FILES['image_data']['size'] <= MAX_FILE_SIZE) {
$sizeOK = true;
}

// check that file is of a permitted MIME type
foreach ($permitted as $type) {
if ($type == $_FILES['image_data']['type']) {
$typeOK = true;
break;
}
}

if ($sizeOK && $typeOK) {
$success = move_uploaded_file($_FILES['image_data']['tmp_name'], UPLOAD_DIR.'/'.$file);
}

  $insertSQL = sprintf("INSERT INTO postingTable (post_id, post_title, product_name, user_id, post_date, buy_or_share, category_name, image_data) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
					   GetSQLValueString($_POST['post_id'], "int"),
					   GetSQLValueString($_POST['post_title'], "text"),
					   GetSQLValueString($_POST['product_name'], "text"),
					   GetSQLValueString($_POST['user_id'], "int"),
					   GetSQLValueString($_POST['post_date'], "defined", 'NOW()'),
					   GetSQLValueString($_POST['buy_or_share'], "text"),
					   GetSQLValueString($_POST['category_name'], "text"),
					   GetSQLValueString($_FILES['image_data'], "text"));
  mysql_select_db($database_connUser, $connUser);
  $Result1 = mysql_query($insertSQL, $connUser) or die(mysql_error());

  $insertGoTo = "userprofile.php";
  if (isset($_SERVER['QUERY_STRING'])) {
	$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
	$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
}



Hi ninethousandfeet

I think that the issue is with your code, rather than with the move_uploaded_file. You don't seem to be doing any sort of debugging / error reporting, and some things are definately incorrect within your code.

I've adapted your code a little, though I wouldn't personally write my image uploads this way.

define('UPLOAD_DIR', '/domains/mysite.com/public_html/upload');

if($_POST['MM_insert'] == 'form1')
{
	if($_FILES['image_data']['error'] == 0 && $_FILES['image_data']['size'] <= number_format(51200/1024, 1))
	{
		$filename = str_replace(' ', '_', $_FILES['image_data']['name']);
		
		$filetypes = array(
			'image/gif',
			'image/jpeg',
			'image/png'
		);
		
		if(in_array($_FILES['image_data']['type'], $filetypes))
		{
			if(is_dir(UPLOAD_DIR))
			{
				if (move_uploaded_file($_FILES['image_data']['tmp_name'], UPLOAD_DIR.'/'.$file))
				{
					  $insertSQL = sprintf("INSERT INTO postingTable (post_id, post_title, product_name, user_id, post_date, buy_or_share, category_name, image_data) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
										   GetSQLValueString($_POST['post_id'], "int"),
										   GetSQLValueString($_POST['post_title'], "text"),
										   GetSQLValueString($_POST['product_name'], "text"),
										   GetSQLValueString($_POST['user_id'], "int"),
										   GetSQLValueString($_POST['post_date'], "defined", 'NOW()'),
										   GetSQLValueString($_POST['buy_or_share'], "text"),
										   GetSQLValueString($_POST['category_name'], "text"),
										   GetSQLValueString($_FILES['image_data'], "text"));
					mysql_select_db($database_connUser, $connUser);
					$Result1 = mysql_query($insertSQL, $connUser) or die(mysql_error());
					
					$insertGoTo = "userprofile.php";
					if (isset($_SERVER['QUERY_STRING'])) {
						$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
						$insertGoTo .= $_SERVER['QUERY_STRING'];
					}
					header(sprintf("Location: %s", $insertGoTo));
				}
				else
				{
					die("Could not upload file");
				}
			}
			else
			{
				die(UPLOAD_DIR . ' is not a valid directory');
			}
		}
		else
		{
			die($_FILES['image_data']['type'] . ' is an invalid file type');
		}
	}
	else
	{
		die('Upload contains errors or exceeds the maximum filesize');
	}
}



For starters your maximum file size is very low, and the UPLOAD DIR is using an absolute path, though it may actually be searching from within public_html/ (so you only need to specify /upload/)

You specified KB onto the end of your file size, but the value ['size'] doesn't actually contain KB so that will always fail. I haven't tested the code I written above so apologies if I have made a mistake, though you if there are no errors you will find it will die if something doesn't pass a condition.

I strongly suggest you get into the habbit of printing the values of variables and arrays to the page, to make sure your own calculations are correct. You can also take advantage of things such as var_dump() to print full arrays to the screen, so var_dump($_FILES['image_data']); and you can use things such as is_dir or is_file to check the paths to files and directories are correct.

Hope this Helps.
Was This Post Helpful? 0
  • +
  • -

#3 ninethousandfeet@msn.com  Icon User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 310
  • Joined: 09-February 09

Re: Upload image file to Directory, and image name to db

Posted 28 March 2009 - 05:06 PM

hi Gevie,

thank you for your response. i was able to get everything working before you sent this over, but i'm not sure if it is as efficient/secure as maybe it should be. would you mind taking a look and let me know what you think? also, what file size would you recommend? and is there still something wrong with my path?
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 51200);
// define constant for upload folder
$uploadDIR = '/home/me/domains/mysite.com/public_html/upload';
// assign simpler variable
$file = str_replace(' ', '_', $_FILES["image_data"]["name"]);
$fileTemp = $_FILES['image_data']['tmp_name'];

// convert the maximum size to KB
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';

$fileOK = false;
if (!empty($_FILES['image_type']) && !empty($file)) {
if (($_FILES["image_data"]["type"] == "image/gif")
  || ($_FILES["image_data"]["type"] == "image/jpeg")
  || ($_FILES["image_data"]["type"] == "image/pjpeg")
  || ($_FILES["image_data"]["type"] == "image/png" )
  && ($_FILES["image_data"]["size"] < MAX_FILE_SIZE)) {
	$fileOK = true;
} else {
	$error['sizetype'] = 'File must be in either gif, jpeg, pjpeg, or png AND less than 50kb.';
}
}
if (!$error) {
$username = $_SESSION['MM_Username'];
ini_set('date.timezone','America/Los Angeles');
$now = date('Y-m-d-His');
if (!is_dir("$uploadDIR/$username")) {
mkdir("$uploadDIR/$username", 0777, true);
}
			
  $insertSQL = sprintf("INSERT INTO postingTable (post_id, post_title, product_name, user_id, post_date, buy_or_share, category_name, image_data, image_type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
					   GetSQLValueString($_POST['post_id'], "int"),
					   GetSQLValueString($_POST['post_title'], "text"),
					   GetSQLValueString($_POST['product_name'], "text"),
					   GetSQLValueString($_POST['user_id'], "int"),
					   GetSQLValueString($_POST['post_date'], "defined", 'NOW()'),
					   GetSQLValueString($_POST['buy_or_share'], "text"),
					   GetSQLValueString($_POST['category_name'], "text"),
					   GetSQLValueString($_FILES['image_data']['name'], "text"),
					   GetSQLValueString($_FILES['image_data']['type'], "text"));
  mysql_select_db($database_connUser, $connUser);
  $Result1 = mysql_query($insertSQL, $connUser) or die(mysql_error());

  $insertGoTo = "userprofile.php";
  if (isset($_SERVER['QUERY_STRING'])) {
	$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
	$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  if (!file_exists("$uploadDIR/$username/$file")) {
  move_uploaded_file($fileTemp, "$uploadDIR/$username/$file");
  } else {
	  mkdir("$uploadDIR/$username/$now");
	  move_uploaded_file($fileTemp, "$uploadDIR/$username/$now/$file");
  }
  header(sprintf("Location: %s", $insertGoTo));
}
}


Was This Post Helpful? 0
  • +
  • -

#4 Gevie  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 29
  • Joined: 06-April 08

Re: Upload image file to Directory, and image name to db

Posted 28 March 2009 - 05:13 PM

Hi ninethousandfeet,

If you don't mind waiting 15 minutes or so I will present you with an updated and commented version.

Well done on fixing your issue, your path must be working as absolute which is great! No worries there :)

Thanks
Was This Post Helpful? 0
  • +
  • -

#5 Gevie  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 29
  • Joined: 06-April 08

Re: Upload image file to Directory, and image name to db

Posted 28 March 2009 - 05:30 PM

<?php

	// define the maximum upload (6.2mb)
	define ('MAX_FILE_SIZE', 51200);

	// Define the upload directory
	$uploadDIR 	= '/home/me/domains/mysite.com/public_html/upload';

	// Grab the file extension
	$ext		= substr(strrchr($_FILES['image_data']['name'], '.'), 1);
	
	// Generate a unique 8 character string
	$filename 	= substr(sha1($_FILES['image_data']['name']), 0, 8);
	
	// Ammend the timestamp and extension onto the string
	$filename	.= time() . $ext;

	// Temporary Variables
	$fileTemp 	= $_FILES['image_data']['tmp_name'];
	$error		= array();

	// If there was no error uploading the file
	// (Check $_FILES on PHP for more information)
	if($_FILES['image_type']['error'] == 0)
	{
		// An array of image mime types
		$filetypes = array(
			'image/gif',
			'image/jpeg',
			'image/pjpeg',
			'image/png'
		);
		
		// Check that the type exists in the array above
		if(!in_array($_FILES['image_type']['type'], $filetypes))
		{
			// Invalid filetype, add an error
			$error[] = 'File must be either a gif, jpeg, pjpeg or png';
		}
		
		// Check the file size isn't more than the limit (6.2mb)
		if($_FILES['image_type']['size'] > MAX_FILE_SIZE)
		{
			// Size too large, add an error
			$error[] = 'Files must be less than ' . MAX_FILE_SIZE . 'KB';
		}
		
		// If there are no errors then proceed
		if(count($error) == 0)
		{
			// Set the username
			$username = $_SESSION['MM_Username'];
			ini_set('date.timezone','America/Los Angeles');
			$now = date('Y-m-d-His');
			
			// Check if the directory to upload too exists
			if (!is_dir("$uploadDIR/$username"))
			{
				// Directory doesn't exist, lets create it
				mkdir("$uploadDIR/$username", 0777, true);
			}
			
			// Generate a SAFE SQL Query
			  $insertSQL = 	sprintf("INSERT INTO postingTable (post_id, post_title, product_name, user_id, post_date, buy_or_share, category_name, image_data, image_type) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
   							GetSQLValueString($_POST['post_id'], "int"),
							GetSQLValueString($_POST['post_title'], "text"),
							GetSQLValueString($_POST['product_name'], "text"),
							GetSQLValueString($_POST['user_id'], "int"),
							GetSQLValueString($_POST['post_date'], "defined", 'NOW()'),
							GetSQLValueString($_POST['buy_or_share'], "text"),
							GetSQLValueString($_POST['category_name'], "text"),
							GetSQLValueString($_FILES['image_data']['name'], "text"),
							GetSQLValueString($_FILES['image_data']['type'], "text"));
			  mysql_select_db($database_connUser, $connUser);
			  
			  // Execute the Query (Better done after the upload in all honesty)
			  $Result1 = mysql_query($insertSQL, $connUser) or die(mysql_error());
			
			// Determine the path to redirect too and parameters
 			$insertGoTo = "userprofile.php";
			  if (isset($_SERVER['QUERY_STRING']))
			  {
				$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
				$insertGoTo .= $_SERVER['QUERY_STRING'];
			}
			
			// If the file doesn't exist already (Which it probably never will do thanks to the unique name)
			  if (!file_exists("$uploadDIR/$username/$filename"))
			  {
				  // Upload the new file
				  move_uploaded_file($fileTemp, "$uploadDIR/$username/$filename");
			  }
			  else
			  {
				  // Otherwise create a new directory and upload the file
				  mkdir("$uploadDIR/$username/$now");
				  move_uploaded_file($fileTemp, "$uploadDIR/$username/$now/$filename");
			  }
			  
			  // All done! Redirect the user
			  header(sprintf("Location: %s", $insertGoTo));
			
		}
	}
	else
	{
		// Errors present on upload
		$error[] = 'There was an error uploading your file';
	}

	// The user hasn't been re-directed yet, so lets show them all the errors
	foreach($error as $msg)
	{
		echo $msg . "<br />";
	}


?>



By the way, I missed a 0 from your filesize when I first read it, your filesize is quite large! I hope this helps, any questions - just ask away.
Was This Post Helpful? 1
  • +
  • -

#6 ninethousandfeet@msn.com  Icon User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 310
  • Joined: 09-February 09

Re: Upload image file to Directory, and image name to db

Posted 29 March 2009 - 02:17 AM

what do you think about the update and delete pages? i'm reading some info on how to update and delete image files and i'm a little unclear on how to accomplish it... with my given code, would i need to unlink() the directory in an IF statement before i submit the updateSQL? each time the update post is made (whether a new image is added or nothing is added, a new folder is created and then no image is displayed when i go back to view the page after the update... any suggestions?
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {

// error array
$error = array();

// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 51200);
// define constant for upload folder
$uploadDIR = '/home/me/domains/mysite.com/public_html/upload';
// assign simpler variable
$file = str_replace(' ', '_', $_FILES["image_data"]["name"]);
$fileTemp = $_FILES['image_data']['tmp_name'];

// convert the maximum size to KB
$max = number_format(MAX_FILE_SIZE/1024, 1).'KB';

$fileOK = false;
if (!empty($_FILES['image_type']) && !empty($file)) {
if (($_FILES["image_data"]["type"] == "image/gif")
  || ($_FILES["image_data"]["type"] == "image/jpeg")
  || ($_FILES["image_data"]["type"] == "image/pjpeg")
  || ($_FILES["image_data"]["type"] == "image/png" )
  && ($_FILES["image_data"]["size"] < MAX_FILE_SIZE)) {
	$fileOK = true;
} else {
	$error['sizetype'] = 'File must be in either gif, jpeg, pjpeg, or png AND less than 6.2MB.';
}
}
if (!$error) {
$username = $_SESSION['MM_Username'];
ini_set('date.timezone','America/Los Angeles');
$now = date('Y-m-d-His');
if (!is_dir("$uploadDIR/$username")) {
mkdir("$uploadDIR/$username", 0777, true);
}
  $updateSQL = sprintf("UPDATE postingTable SET post_title=%s, product_name=%s, user_id=%s, buy_or_share=%s, category_name=%s, image_data=%s, image_type=%s WHERE post_id=%s",
					   GetSQLValueString($_POST['post_title'], "text"),
					   GetSQLValueString($_POST['product_name'], "text"),
					   GetSQLValueString($_POST['user_id'], "int"),
					   GetSQLValueString($_POST['buy_or_share'], "text"),
					   GetSQLValueString($_POST['category_name'], "text"),
					   GetSQLValueString($_POST['image_data'], "text"),
					   GetSQLValueString($_POST['image_type'], "text"),
					   GetSQLValueString($_POST['post_id'], "int"));

  mysql_select_db($database_connUser, $connUser);
  $Result1 = mysql_query($updateSQL, $connUser) or die(mysql_error());

  $updateGoTo = "userprofile.php";
  if (isset($_SERVER['QUERY_STRING'])) {
	$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
	$updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  if (!file_exists("$uploadDIR/$username/$file")) {
  move_uploaded_file($fileTemp, "$uploadDIR/$username/$file");
  } else {
	  mkdir("$uploadDIR/$username/$now");
	  move_uploaded_file($fileTemp, "$uploadDIR/$username/$now/$file");
  }
  header(sprintf("Location: %s", $updateGoTo));
}
}
?>


Was This Post Helpful? 0
  • +
  • -

#7 ninethousandfeet@msn.com  Icon User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 310
  • Joined: 09-February 09

Re: Upload image file to Directory, and image name to db

Posted 29 March 2009 - 10:06 PM

okay, so i am able upload the images okay now... but i am having trouble displaying the files. when a user uploads an image, two things happen. the image name from the users computer and the type go to the db and the actual image file/name is encrypted and sent to the directory on my host.
then, to display i do something like this below, but it doesn't work... i think b/c it is getting the name from the db but the name in the directory obviously doesn't match b/c it has been encrypted when uploaded.
<?php if ($row_getPost['image_data'] != NULL) { // Show if picture is NOT empty ?>
  <img src = "http://www.shareyourdiscount.com/upload/<?php echo $row_getPost['username']?>/<?php echo $row_getPost['image_data']?>" />
  <?php } // Show if pic not empty ?>



any suggestions on how i can allow a user to view the image they sent to the directory?
thank you!
Was This Post Helpful? 0
  • +
  • -

#8 Guest_cesar*


Reputation:

Re: Upload image file to Directory, and image name to db

Posted 06 December 2010 - 04:47 PM

i create a folder from a form like this:

<form name="form1" method="post" action="register.php" style="padding:5px;">
        <p><br>
          Name: 
          <input name="full_name" type="text" id="full_name">
         	<p><br>
          business : 
          <input name="user_name" type="text" id="user_name">
          
</form>



so in the business input the user is create the folder name, so then


mkdir ("$user_name",'0700');


but my questions is when users are login in , and they want to upload some image to the folder that they 've created .

$target = "$user_name/"; 
$target = $target . basename( $_FILES['photo']['name']);


is correct put $user_name here? $target= "$user_name/";


thank in advance

MOD EDIT: When posting code...USE CODE TAGS!!!

:code:

This post has been edited by JackOfAllTrades: 06 December 2010 - 04:57 PM

Was This Post Helpful? 0

Page 1 of 1