×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

File Upload and Conversion

File Upload and Conversion

File Upload and Conversion

(OP)
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?

CODE --> 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.

CODE --> 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;
} 

RE: File Upload and Conversion

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; 

RE: File Upload and Conversion

(OP)
No, I want to enter only the file name into the table, not the path.

RE: File Upload and Conversion

fine. then that is contained in your $Message variable.

RE: File Upload and Conversion

(OP)
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.

RE: File Upload and Conversion

Given that by the time the conversion is done you know the record id why can't you just do an update?

RE: File Upload and Conversion

(OP)
Well, I can of course, but what about new entries?

RE: File Upload and Conversion

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.

RE: File Upload and Conversion

After looking at the code, I too am puzzled why can't you do this?:

CODE

if ($AdminName && $ImageName && $Description && !$PostID) :
$Message = ConvertImage($_FILES['FileUpload'], "370");
$sqlInsert = sprintf("INSERT INTO albums (AdminName, ImageName, Description) VALUES ('%s','%s', '%s')", $AdminName, $Messsage, $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

RE: File Upload and Conversion

(OP)
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.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close