Get ready for BLACK FRIDAY shopping starting in

Forums

PHP

This topic is locked

PHP Upload Filename to Dbase

Posted 24 Jan 2009 01:43:30
1
has voted
24 Jan 2009 01:43:30 Heather V posted:
Before I post my extensive code, I'd like to know if there's anyone here who is familiar with uploading filenames into a database after a file has been uploaded?

To be more specific, I have a form that has an upload prompt plus many other fields to fill out on the form that are text-based. I'd like for the upload to work and copy to a specific folder and also have the whole form (including the filename of the file) post to a record in a database table. Is there anyone available to help?

Replies

Replied 27 Jan 2009 13:03:48
27 Jan 2009 13:03:48 Alan C replied:
Hi Heather,
yes, I've done this, in my case it was uploading images, then resizing them, modifying the filename by adding a pre-fix to reflect the id of the person who uploaded them, then storing the re-sized images in different folders.
I store the filename once in a table then can pick up the various images by appending it to the path.
What do you want to do and I'll dig out my code so see just how I did it, I don't think it was too difficult.
Replied 31 Jan 2009 11:28:29
31 Jan 2009 11:28:29 Heather V replied:
QuoteHi Heather,
yes, I've done this, in my case it was uploading images, then resizing them, modifying the filename by adding a pre-fix to reflect the id of the person who uploaded them, then storing the re-sized images in different folders.
I store the filename once in a table then can pick up the various images by appending it to the path.
What do you want to do and I'll dig out my code so see just how I did it, I don't think it was too difficult.


Well, I have this code and I can't seem to get it to post the file to the server nor post the filename to the database:

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 211200);

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
    // define constant for upload folder
  define('UPLOAD_DIR', '../../info/docs/employment/');
  // replace any spaces in original filename with underscores
  // at the same time, assign to a simpler variable
  $file = str_replace(' ', '_', $_FILES['empl_dnld_fn']['name']);
  // convert the maximum size to KB
  $max = number_format(MAX_FILE_SIZE/1024, 1).'KB';
  // create an array of permitted MIME types
  $permitted = array('application/pdf');
  // begin by assuming the file is unacceptable
  $sizeOK = false;
  $typeOK = false;
  
  // check that file is within the permitted size
  if ($_FILES['empl_dnld_fn']['size'] > 0 && $_FILES['empl_dnld_fn']['size'] <= MAX_FILE_SIZE) {
    $sizeOK = true;
	}

  // check that file is of an permitted MIME type
  foreach ($permitted as $type) {
    if ($type == $_FILES['empl_dnld_fn']['type']) {
      $typeOK = true;
	  break;
	  }
	}
  
    if ($sizeOK && $typeOK) {
    switch($_FILES['empl_dnld_fn']['error']) {
	  case 0:
        // check if a file of the same name has been uploaded
		if (!file_exists(UPLOAD_DIR.$file)) {
		  // move the file to the upload folder and rename it
		  $success = move_uploaded_file($_FILES['empl_dnld_fn']['tmp_name'], UPLOAD_DIR.$file);
		  }
		else {
		  // get the date and time
		  ini_set('date.timezone', 'Europe/London');
		  $now = date('Y-m-d-His');
		  $success = move_uploaded_file($_FILES['empl_dnld_fn']['tmp_name'], UPLOAD_DIR.$now.$file);
		  }
		  
$insertSQL = sprintf("INSERT INTO empl_dnlds (empl_dnld_title, empl_dnld_fn) VALUES (%s, %s)",
                       GetSQLValueString($_POST['empl_dnld_title'], "text"),
                       GetSQLValueString($_FILES['empl_dnld_fn'], "text"));

  mysql_select_db($database_wvgsadmin, $wvgsadmin);
  $Result1 = mysql_query($insertSQL, $wvgsadmin) or die(mysql_error());


if ($success) {
  $insertGoTo = "../info/employment/empl_app_list.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
else {
		  $result = "Error uploading $file. Please try again.";
		  }
	    break;
	  case 3:
		$result = "Error uploading $file. Please try again.";
	  default:
        $result = "System error uploading $file. Contact webmaster.";
	  }
    }
  elseif ($_FILES['empl_dnld_fn']['error'] == 4) {
    $result = 'No file selected';
	}
  else {
    $result = "$file cannot be uploaded. Maximum size: $max. Acceptable file type: .pdf";
	}
  }



<form action="" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
		<p>
		<label for="empl_dnld_fn">Upload document:</label>
		<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
        <input type="file" name="empl_dnld_fn" id="empl_dnld_fn" /></p>
		<span class="small">
		<ul>
		<li>to minimize confusion, filename should be unique to the Staff you are uploading for</li>
		<li>document file size is limited to 200K</li>
		<li>if you upload a file with the same filename, the new file will be given a date added to the filename</li>
</ul>
</span>
		<p><input type="submit" name="upload" id="upload" value="Upload Image" /></p>
</form>


Thank you for taking a look at this for me!
toad78
Replied 03 Feb 2009 21:03:05
03 Feb 2009 21:03:05 Alan C replied:
Hi Heather,
your form looks remarkably like mine, we probably worked from similar sources

it's ages since I wrote this so I am puzzling over some of the code, I do something very similar after the submit button is pressed, I am a bit more paranoid that you when dealing with the user input, so I hit the filename rather hard to prevent anything odd coming through, and force it to all lower case. I only accept jpg images and force the extension to .jpg to make life easier for myself later. I also restrict the length of the image filename and tag it with the owner's user_id and property_id, because there can be many images per user, so that if a user asks for their account to be deleted it's easy to find all their images.
I have skimmed through your code, it looks like it does all the right kind of things, I'm working on a project at the moment so can't take too much effort out of that . . . here is some of the code from my original, you should see the similarity, I store variations of the image after resizing and producing a thumbnail.

		 # was submit button pressed, if it was then process the uploaded image and show back button
		 if(isset($_POST["Submit"]) && $_POST["Submit"] == 'Send photograph' )
{ # call to self with uploaded image

$uploaddir = '../property_images/'; // these paths need to be relative because of server restriction
$main_images=$uploaddir.'main/';
$thumb_images=$uploaddir.'thumbs/';
$original_filename=basename($_FILES['most_recent']['name']);
# some id info, so pre-pend the filename with the user's name and property id for my benefit later
# check length of filename here and crop it if it is too long
# do it here so that odd chars and spaces etc will be filtered out later
if (strlen($original_filename)>MAX_IMAGE_NAME_LENGTH) $original_filename=substr($original_filename,(strlen($original_filename)-MAX_IMAGE_NAME_LENGTH), MAX_IMAGE_NAME_LENGTH);
$original_filename=$actual_p_id.'_'.$original_filename;

# now get rid of suspect chars
$new_filename=preg_replace('/[^a-z0-9._-]/','',strtolower($original_filename)); //strips whitespace and odd chars
$new_filename=preg_replace('/jpeg/','jpg',$new_filename); // change jpeg to jpg

$uploadfile = $uploaddir . $new_filename;                 // full path, keep this name so file can be deleted later

if (move_uploaded_file($_FILES['most_recent']['tmp_name'], $uploadfile)) {
   echo $CSS->Tag('h3',"Success! your photograph has been successfully uploaded to tagetsite.com".'<br />');
   $upload_error='none'; // error marker
#
# have a look at the uploaded file and determine whether it is acceptable or not
#
$image_info=getimagesize($uploadfile); // transfer details to array

#$details=$CSS->ShowArray($image_info); // monitoring use

if(!strpos($image_info['mime'],'jpeg'))
	{ $upload_error='not-jpeg';
	} // end jpeg test
		
# file size details are in $image_info
$width=$image_info[0];
$height=$image_info[1];
$aspect_ratio=$width/$height;

a few things to note, this is just the bit that looks at the filename and mime type, even though the file has a .jpg extension it might not be an image file, that's why I test teh mime type, not sure if that really does what I think it does.
Once I have the image I need to check its shape, because I'm going to display it on my pages, so it has to be fitted into a landscape rectangle of a certain aspect ratio, I use ImageMagick to resize and pad out the image, so i have left that part out. It works very much like yours with an error code and then a switch statement.

This lot is hand-coded, you'll notice the -> notation that uses some methods in an object or two which is some re-usable code. My database store is part of another object that handles minor updates because it saves keep writing sql. This is what it looks like

	# next line updates db table with just the filename, add the path when needed
	$store_filename=$database->update_to('properties', 'p_image_path', $new_filename, 'text', 'p_id', $actual_p_id);
	# finally get rid of the uploaded file
	unlink($uploadfile);


the method in the object is just a wrapper that writes a query then executes it to update a single record, the parameters are . . .
table name
column name to update
value to use for update (ie new value)
value type
column to be used in WHERE clause
value to use in where clause

I would be very wary of using values out of the $_GET array without checking them, there are some weird people out there who will try to break your scripts, and try sql injection, I'm paranoid I admit it!

let me know how you get on

Reply to this topic