Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File Upload and Conversion

Status
Not open for further replies.

PCHomepage

Programmer
Feb 24, 2009
609
US
Some time ago I created a form with some functions for uploading files to my Web server. No real problem there but then I decided to also repurpose a function for resizing the image but I am having difficulty in getting the new file name and placing it into the table. I know why but I'm not sure what to do about it. Any ideas?

PHP:
<?php
include_once $_SERVER ['DOCUMENT_ROOT'] . "/functions/common.php";
// Limit access to Administrators
accessRedirect(3);
global $Message;
global $ActionType;
global $PostID;

$editFormAction = $_SERVER['PHP_SELF'];

// Select form
$searchSQL = "SELECT ID, AdminName AS SelectText
			  FROM albums 
			  ORDER BY AdminName";

// Updates and Inserts
$AdminName = (isset($_POST["AdminName"]) && !empty($_POST["AdminName"])) ? $_POST["AdminName"] : "";
$ImageName = (isset($_POST["ImageName"]) && !empty($_POST["ImageName"])) ? $_POST["ImageName"] : "";
$Description = (isset($_POST["Description"]) && !empty($_POST["Description"])) ? addslashes($_POST["Description"]) : "";
$PostID = (isset($_POST["ID"]) && !empty($_POST["ID"])) ? $_POST["ID"] : "";

if ($AdminName && $ImageName && $Description && !$PostID) :
	$sqlInsert = sprintf("INSERT INTO albums (AdminName, ImageName, Description)
				  VALUES ('%s','%s', '%s')",
				  $AdminName,
				  $ImageName,
				  $Description);
	DBConnect($sqlInsert, "Insert", "dbname");
	$PostID = DBConnect("No Query Needed", "NewID", "dbname");
	$Message = ConvertImage($_FILES['FileUpload'], "370");
elseif ($PostID) :
	$sqlUpdate = sprintf("UPDATE albums 
						  SET AdminName='%s', ImageName='%s', Description='%s' 
						  WHERE ID=%u",
				  $AdminName,
				  $ImageName,
				  $Description,
				  $PostID);
	DBConnect($sqlUpdate, "Update", "dbname");
	$Message = ConvertImage($_FILES['FileUpload'], "370");
endif;

// Open selected record to view
$SearchID = (isset($_POST["SearchID"]) && !empty($_POST["SearchID"])) ? $_POST["SearchID"] : "";
$sqlView = "SELECT * FROM albums WHERE ID='".$SearchID."' OR ID='".$PostID."'";
$rowView = DBConnect($sqlView, "Select", "dbname");

$AdminName = ($rowView['AdminName']) ? $rowView['AdminName'] : $AdminName;
$ImageName = ($rowView['ImageName']) ? $rowView['ImageName'] : $rowView['ImageName'];
$Description = ($rowView['Description']) ? $rowView['Description'] : $Description;
$PostID = ($rowView['ID']) ? $rowView['ID'] : $PostID;

?><!DOCTYPE HTML>
<html>
<head>
<title>Photo Album Administration</title>
	<?php include("../includes/pageheader.php"); ?>
<script language="JavaScript">
<!--
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateEmpty(theForm.AdminName);
  reason += validateEmpty(theForm.Description);

  if (reason != "") {
    alert("Missing Required Entry Details\n\n" + reason);
    return false;
  }

  return true;
}

function validateEmpty(fld) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "Required field(s) missing.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;   
}
// -->
</script>
</head>

<body id="Body">

<div id="CenterContent">

	<?=SearchForm($searchSQL, $editFormAction, $PostID, "dbname");?>

	<?php 
	if (isset($_SESSION['ActionType']) && !empty($_SESSION['ActionType'])) :
		$ActionType = $_SESSION['ActionType']; 
		$_SESSION['ActionType'] = "";
	endif;
	?>

	<form method="POST" onsubmit="return validateFormOnSubmit(this)" enctype="multipart/form-data" name="AdminDMVforms" action="<?=$editFormAction?>">
		<fieldset>
			<legend for="PhotoAlbums">Photo Albums</legend>
			<p><label for="AdminName">Admin Name</label>
				<input type="text" name="AdminName" value="<?=$AdminName?>" size="25">
			<p><label for="Description">Description</label>
				<textarea name="Description" rows="5" cols="65" id="Description"><?=stripslashes($Description)?></textarea>
				<input type="hidden" name="ImageName" value="<?=$Message?>" size="25">
			<p><p><label for="File">Select File</label>
				<input name="FileUpload" type="file">
				<input type="hidden" name="ID" value="<?=$rowView['ID']?>">
	<?php
	if (isset($rowView['ImageName']) && !empty($rowView['ImageName'])) :
		Message($rowView['ImageName']."<br>$Message has been uploaded!");
	endif;
		FormSubmit($PostID, $editFormAction, "Delete this Album entry?");
	?></fieldset>	
  </form>

</div> 

</body>
</html>

Here is the upload and conversion function.

PHP:
function ConvertImage($ImgFile, $MaxDim) {
    $folderPerms = 0755;
    $FilePath = realpath($_SERVER['DOCUMENT_ROOT']). DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . "album" . DIRECTORY_SEPARATOR;
    clearstatcache();

       // if ($error == UPLOAD_ERR_OK):
            $tmp_name = $ImgFile['tmp_name'];
            $ImgName = $ImgFile['name'];
            list($Imgwidth, $Imgheight, $Imgtype, $attr) = getimagesize($tmp_name);
			$NewName = str_replace(' ','_', strtolower(trim(pathinfo($ImgName,PATHINFO_FILENAME)))).".jpg";

            switch ($Imgtype) :
                case 1 : $src = imagecreatefromgif($tmp_name);  break;
                case 2 : $src = imagecreatefromjpeg($tmp_name); break;
                case 3 : $src = imagecreatefrompng($tmp_name);  break;
                case 6 : $src = imagecreatefrombmp($tmp_name); break; // Custom function
                default : die("Unsupported image type. You may upload only JPG, GIF, PNG or BMP images.");
            endswitch;
			
			if($src == false) die("Unable to create image");

                if($Imgwidth > $MaxDim):
                    $newWidth = $MaxDim;
                    $newHeight = round($Imgheight * ($newWidth / $Imgwidth));
                else:
                    $newHeight = $Imgheight;
                    $newWidth = $Imgwidth;
                endif;

				$tmp = imagecreatetruecolor($newWidth, $newHeight);
                imagecopyresampled($tmp, $src, 0, 0, 0, 0,$newWidth, $newHeight, $Imgwidth, $Imgheight);
                $__filename = sprintf($FilePath . $NewName,'');
				$result = imagejpeg($tmp, $__filename, 75);
                //$return[] = array('filename'=>$__filename, 'original'=>false, 'height'=>$newHeight, 'width'=>$newWidth, 'status'=>$result);
				$return = $NewName;
            @unlink($tmp_name);
       // endif;
    return $return;
}
 
this line
Code:
$Message = ConvertImage($_FILES['FileUpload'], "370");

is misleading. $Message is in fact the fileName without the path. If you want the whole path and file name then change this
Code:
$return = $NewName;
to
Code:
$return = $__filename;
 
No, I want to enter only the file name into the table, not the path.
 
fine. then that is contained in your $Message variable.
 
Yes, I know but $Message is being declared after the database inserts and I can see no way to place it before them and still have it work. I suppose I could put the functionality into the ConvertImage() but that would be somewhat problematic for new entries even though it would work okay for existing one. If I do that, I can probably also add some facility to delete the old image if a new one is being uploaded in its place.
 
Given that by the time the conversion is done you know the record id why can't you just do an update?
 
you do a second update after the if ... endif block.

but we don't know your database schema here. if you are inserting the image file name into the same table (Albums), why don't you just do the convertImage before the if ... endif block?

I'm clearly missing something.
 
After looking at the code, I too am puzzled why can't you do this?:
Code:
if ($AdminName && $ImageName && $Description && !$PostID) :
[indent][indent][indent][b][COLOR=#A40000] $Message = ConvertImage($_FILES['FileUpload'], "370");[/color][/b][/indent][/indent][/indent]
	$sqlInsert = sprintf("INSERT INTO albums (AdminName, ImageName, Description)
				  VALUES ('%s','%s', '%s')",
				  $AdminName,
				  [b][COLOR=#A40000]$Messsage[/color][/b],
				  $Description);
	DBConnect($sqlInsert, "Insert", "dbname");
	$PostID = DBConnect("No Query Needed", "NewID", "dbname");
	
elseif ($PostID) :
	$sqlUpdate = sprintf("UPDATE albums 
						  SET AdminName='%s', ImageName='%s', Description='%s' 
						  WHERE ID=%u",
				  $AdminName,
				  $ImageName,
				  $Description,
				  $PostID);
	DBConnect($sqlUpdate, "Update", "dbname");
	$Message = ConvertImage($_FILES['FileUpload'], "370");
endif;



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
I guess my nose got in the way of the obvious but I spotted it before seeing your reply. Thank you and it works now! Now that it's working, I had to add a way to make it update the text portions of an entry even if a new photo was not uploaded but that was easy to do. There are still a few small bugs but they are unrelated to this question.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top