Jump to content

Recommended Posts

I have a script that I modified to insert an image of a specific size into a folder and also insert the final image name into a database column. Below is my current code. When I run the script, all of the information is submitted into the database correctly except for the filename. The image is correctly uploaded to the images folder with the correct dimensions. I think it may just be an incorrect syntax error. Any help is appreciated.

 

<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);

  $logoutGoTo = "logout.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php require_once('../Connections/connect.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

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

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "insert")) {
}

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

if (array_key_exists('upload', $_POST)) {

  $insertSQL = sprintf("INSERT INTO workout (Name, Type, Hyperlink, `Description`, Image, Profit) VALUES (%s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['Name'], "text"),
                       GetSQLValueString($_POST['Type'], "text"),
                       GetSQLValueString($_POST['Hyperlink'], "text"),
                       GetSQLValueString($_POST['Description'], "text"),
                       GetSQLValueString("images/".'$thumb_name', "text"),
                       GetSQLValueString($_POST['Profit'], "double"));

  mysql_select_db($database_connect, $connect);
  $Result1 = mysql_query($insertSQL, $connect) or die(mysql_error());

$workout = $_POST['Name'];

// define constant for upload folder
define('UPLOAD_DIR', 'C:/wamp/www/theworkoutstore/images/');
// replace any spaces in original filename with underscores
// at the same time, assign to a simpler variable
$file = str_replace(' ', '_', $_FILES['image']['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('image/gif','image/jpeg','image/pjpeg','image/png');
// begin by assuming the file is unacceptable
$sizeOK = false;
$typeOK = false;
// check that file is within the permitted size
if ($_FILES['image']['size'] > 0 && $_FILES['image']['size'] <= MAX_FILE_SIZE) {
$sizeOK = true;
}

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

  if ($sizeOK && $typeOK) {
    switch($_FILES['image']['error']) {
      case 0:
  // define constants
  define('THUMBS_DIR', 'c:/wamp/www/theworkoutstore/images/');
  define('MAX_WIDTH', 150);
  define('MAX_HEIGHT', 150);
  
// process the uploaded image
if (is_uploaded_file($_FILES['image']['tmp_name'])) {
$original = $_FILES['image']['tmp_name'];
    // begin by getting the details of the original
    list($width, $height, $type) = getimagesize($original);
// calculate the scaling ratio
    if ($width <= MAX_WIDTH && $height <= MAX_HEIGHT) {
      $ratio = 1;
      }
    elseif ($width > $height) {
      $ratio = MAX_WIDTH/$width;
      }
    else {
      $ratio = MAX_HEIGHT/$height;
      }
// strip the extension off the image filename
$imagetypes = array('/\.gif$/', '/\.jpg$/', '/\.jpeg$/', '/\.png$/');
    $name = preg_replace($imagetypes, '', basename($original));

// create an image resource for the original
switch($type) {
      case 1:
        $source = @ imagecreatefromgif($original);
    if (!$source) {
      $result = 'Cannot process GIF files. Please use JPEG or PNG.';
      }
    break;
      case 2:
        $source = imagecreatefromjpeg($original);
    break;
      case 3:
        $source = imagecreatefrompng($original);
    break;
      default:
        $source = NULL;
    $result = 'Cannot identify file type.';
      }
// make sure the image resource is OK
if (!$source) {
  $result = 'Problem copying original';
  }
else {
  // calculate the dimensions of the thumbnail
      $thumb_width = round($width * $ratio);
      $thumb_height = round($height * $ratio);
  // create an image resource for the thumbnail
      $thumb = imagecreatetruecolor($thumb_width, $thumb_height);
  // create the resized copy
  imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
  // save the resized copy
  switch($type) {
        case 1:
      if (function_exists('imagegif')) {
        $success = imagegif($thumb, THUMBS_DIR.$name.'_thb.gif');
        $thumb_name = $name.'_thb.gif';
	    }
      else {
        $success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 50);
	    $thumb_name = $name.'_thb.jpg';
	    }
      break;
    case 2:
      $success = imagejpeg($thumb, THUMBS_DIR.$name.'_thb.jpg', 100);
      $thumb_name = $name.'_thb.jpg';
      break;
    case 3:
      $success = imagepng($thumb, THUMBS_DIR.$name.'_thb.png');
      $thumb_name = $name.'_thb.png';
    }
	if ($success) {
	  $result = "$thumb_name and $workout inserted sucessfully.";
	  }
  // remove the image resources from memory
  imagedestroy($source);
      imagedestroy($thumb);
  }
}
    break;
  case 3:
	$result = "Error uploading $file. Please try again.";
  default:
        $result = "System error uploading $file. Contact webmaster.";
  }
    }
  elseif ($_FILES['image']['error'] == 4) {
    $result = 'No file selected';
}
  else {
    $result = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: gif, jpg, png.";
}
  }
?>
<!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=utf-8" />
<title>Administrator Section - Insert</title>
<style type="text/css">
<!--
body,td,th {
font-family: Calibri;
font-size: 11pt;
color: #000000;
}
.style1 {
color: #FFFFFF;
font-weight: bold;
font-size: 16pt;
}
.style2 {color: #FFFFFF}
-->
</style></head>

<body>
<table width="800" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="800"><img src="../images/banner.png" width="800" height="150" /></td>
  </tr>
  <tr>
    <td bgcolor="#000033"><div align="center"><span class="style1">ADMINISTRATOR SECTION</span></div></td>
  </tr>
  <tr>
    <td><table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
        <tr>
          <td width="20%" valign="top" bgcolor="#000033"><table width="95%" border="0" align="center" cellpadding="5" cellspacing="0">
            <tr>
              <td><a href="index.php" class="style2">Admin Home</a></td>
            </tr>
            <tr>
              <td><a href="<?php echo $logoutAction ?>">Log Out</a></td>
            </tr>
          </table></td>
          <td width="80%" valign="top"><br />
            <table width="90%" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#000000">
              <tr>
                <td bgcolor="#CCCCCC">
                  <div align="center">
                    <?php
                // if the form has been submitted, display result
                if (isset($result)) {
                  echo "<p><strong>$result</strong></p>";
                  }
                ?>
                    </div>
                  <form action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data" name="insert" id="insert">
                  <table width="100%" border="0" align="center" bordercolor="#000000">
                    <tr valign="baseline">
                      <td colspan="2" align="center" nowrap="nowrap">
                      </td>
                      </tr>
                    <tr valign="baseline">
                      <td nowrap="nowrap" align="right">Workout Name:</td>
                      <td><input type="text" name="Name" value="" size="32" /></td>
                    </tr>
                    <tr valign="baseline">
                      <td nowrap="nowrap" align="right">Workout Type:</td>
                      <td><select name="Type">
                          <option value="Muscle Building" <?php if (!(strcmp("Muscle Building", ""))) {echo "SELECTED";} ?>>Muscle Building</option>
                          <option value="Fat Loss" <?php if (!(strcmp("Fat Loss", ""))) {echo "SELECTED";} ?>>Fat Loss</option>
                          <option value="Sports" <?php if (!(strcmp("Sports", ""))) {echo "SELECTED";} ?>>Sports</option>
                          <option value="Women" <?php if (!(strcmp("Women", ""))) {echo "SELECTED";} ?>>Women</option>
                          <option value="Software" <?php if (!(strcmp("Software", ""))) {echo "SELECTED";} ?>>Software</option>
                          <option value="Diet" <?php if (!(strcmp("Diet", ""))) {echo "SELECTED";} ?>>Diet</option>
                        </select>                      </td>
                    </tr>
                    <tr valign="baseline">
                      <td nowrap="nowrap" align="right">Hyperlink:</td>
                      <td><input type="text" name="Hyperlink" value="" size="32" /></td>
                    </tr>
                    <tr valign="baseline">
                      <td nowrap="nowrap" align="right" valign="top">Description:</td>
                      <td><textarea name="Description" cols="50" rows="5"></textarea></td>
                    </tr>
                    <tr valign="baseline">
                      <td nowrap="nowrap" align="right">Image:</td>
                      <td><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
                      <input name="image" type="file" id="image" size="32" /></td>
                    </tr>
                    <tr valign="baseline">
                      <td nowrap="nowrap" align="right">Profit:</td>
                      <td><input type="text" name="Profit" value="" size="32" /></td>
                    </tr>
                    <tr valign="baseline">
                      <td nowrap="nowrap" align="right"> </td>
                      <td><input type="submit" name="upload" id="upload" value="Insert" /></td>
                    </tr>
                  </table>
                  <input type="hidden" name="MM_insert" value="insert" />
                </form></td>
              </tr>
            </table>
          <br /></td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/201968-inserting-image-name-into-database/
Share on other sites

If you are referring to this insert statement (around line 118)

  $insertSQL = sprintf("INSERT INTO workout (Name, Type, Hyperlink, `Description`, Image, Profit) VALUES (%s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['Name'], "text"),
                       GetSQLValueString($_POST['Type'], "text"),
                       GetSQLValueString($_POST['Hyperlink'], "text"),
                       GetSQLValueString($_POST['Description'], "text"),
                       GetSQLValueString("images/".'$thumb_name', "text"),
                       GetSQLValueString($_POST['Profit'], "double"));

I see two problems with it. 

 

First, $thumb_name has not been defined at this point in the program, so it has no value.

 

Second, you have surrounded $thumb_name with single-quotes, so it will not be evaulated, but will be inserted as literally '$thumb_name'.  There is no need to put quote marks around the variable in this particular statement.

 

I did not really go through the rest of the code, so there may be other issues as well.

Probably should.  I would not insert the information into the database until I have verified that the file is valid, and stored it in it's final destination.  Otherwise, you may end up with database entries that reference files that do not exist.

 

Around line 233 might be a good place.

if ($success) {
        // INSERT INTO DATABASE HERE ...

        $result = "$thumb_name and $workout inserted sucessfully.";
}

 

I didn't walk through the entire script, so there may be some issues to workout when you move it (and what you move), but I think that is where it needs to be.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.