exec_upload.php
<?php

  // This form handler is called from upload_cartoons.php. This page contains a form
  // with the following elements (all are form arrays):
  //   - image_file[]: the actual file browser
  //   - tag_id[]: the category of the cartoon (animals, crime, election, etc.)
  //   - description[]: a text description of each cartoon
  //
  // The uploader verifies that all information was included for each image and then
  // copies the full-quality image into a non-web-accessible directory for download
  // following a verified purchase. The image is converted to a small thumbnail for
  // search results and a medium-sized watermarked image for customers to view in
  // order to decide to make a purchase. All files are then placed in the correct
  // location and the image and its associated information is added to the database.

  ini_set("track_errors", true);
  session_start();
  $_SESSION["ERRORS"] = array();
  $_SESSION["UPLOADED_FILES"] = array();

  if (mysql_connect("localhost", "db_user", "db_pass")) {
    if (!mysql_select_db($db_name)) {
      array_push($_SESSION["ERRORS"], "Could not connect to the database: " . mysql_error());
    }
  }
  else {
    array_push($_SESSION["ERRORS"], "Could not connect to the database: " . mysql_error());
  }
  $tblCartoons = "Cartoons";
  $tblTagMap = "TagMap";

  // upload_cartoons.php contains a thorough JavaScript-based validation routine,
  // but double-check here that all information was provided, just in case.
  $files = array();
  for (range(0, count($_POST['image_file'])-1 as $idx) {
    if (
         isset($_POST['tag_id'][$idx])                             &&
         isset($_POST['description'][$idx])                        &&
         isset($_FILES['image_file']['name'][$idx])                &&
         isset($_FILES['image_file']['tmp_name'][$idx])            &&
         is_uploaded_file($_FILES['image_file']['tmp_name'][$idx]) &&
         $_FILES['image_file']['error'][$idx] == 0
       ) {
      $_SESSION["UPLOADED_FILES"][$_FILES['image_file']['name'][$idx]] = "Not attempted";
      array_push($files, array(
                               'orig_filename'  => $_FILES['image_file']['name'][$idx],
                               'local_filename' => $_FILES['image_file']['tmp_name'][$idx],
                               'tag_id'         => $_POST['tag_id'][$idx],
                               'description'    => $_POST['description'][$idx]
                             ));
    }
  }

  // Set some constants and operational parameters
  $image_hires_dir = "/home/client/hires_images"; // not accessible to HTTP
  $image_thumb_dir = "/home/client/html/thumbs";
  $image_basic_dir = "/home/client/html/images";
  $basic_max_dim = 640;
  $thumb_max_dim = 180;
  $jpeg_quality = 75; // out of 100
  $watermark_str = "copyright";
  $watermark_font = 5; // built-in font #5 - fixed

  foreach ( $files as $file_info ) {

    // Set variables and verify/escape those to be used in DB queries
    $orig_filename  = $file_info['orig_filename'];
    $local_filename = $file_info['local_filename'];
    $description    = escape_sql_param($file_info['description']);
    $tag_id         = $file_info['tag_id'];
    if (!preg_match('/^\d+$/', $tag_id)) {
      array_push($_SESSION["ERRORS"], "Could not verify tag id!");
      break;
    }
    $_SESSION["UPLOADED_FILES"][$orig_filename] = "Failed";

    // generate local filenames and copy uploaded hires file
    $new_base_filename = strtoupper(md5($orig_filename)) . "-" . time() . ".jpg";
    $filename_hires = "$image_hires_dir/$new_base_filename";
    $filename_thumb = "$image_thumb_dir/$new_base_filename";
    $filename_basic = "$image_basic_dir/$new_base_filename";
    $prev_err = error_reporting(0);
    $copy_ok = copy($local_filename, $filename_hires); // $local_filename confirmed by is_uploaded_file
    error_reporting($prev_err);

    if ($copy_ok) {

      // Get info from the hires image
      $prev_err = error_reporting(0);
      $img_hires = imagecreatefromjpeg($filename_hires);
      error_reporting($prev_err);
      if ($img_hires) {

        list($hires_w, $hires_h) = getimagesize($filename_hires);
        $hires_max_dim = max($hires_w, $hires_h);
        $hires_x_offset = 0;
        $hires_y_offset = 0;

        // Create the medium-quality (standard/browse) image - resixed and watermarked
        $basic_ratio = $basic_max_dim / $hires_max_dim;
        $basic_w = $hires_w * $basic_ratio;
        $basic_h = $hires_h * $basic_ratio;
        $basic_x_offset = round(($basic_max_dim - $basic_w) / 2);
        $basic_y_offset = round(($basic_max_dim - $basic_h) / 2);
        $img_basic = imagecreatetruecolor($basic_max_dim, $basic_max_dim);
        $white_basic = imagecolorallocate($img_basic, 0xFF, 0xFF, 0xFF);
        imagefill($img_basic, 0, 0, $white_basic);
        imagecopyresampled($img_basic, $img_hires,
                           $basic_x_offset, $basic_y_offset,
                           $hires_x_offset, $hires_y_offset,
                           $basic_w, $basic_h,
                           $hires_w, $hires_h);

        // Watermark the basic image
        $gray_basic = imagecolorallocate($img_basic, 0x80, 0x80, 0x80);
        $watermark_w = imagefontwidth($watermark_font) * strlen($watermark_str);
        $watermark_y = $basic_y_offset + 50;
        $odd_row = 0;
        while ($watermark_y < $basic_y_offset + $basic_h - 50) {
          $watermark_x = $basic_x_offset + 50 + (50 * $odd_row);
          $odd_row = 1 - $odd_row;
          while ($watermark_x < $basic_x_offset + $basic_w - $watermark_w) {
            imagestring($img_basic, $watermark_font, $watermark_x, $watermark_y, $watermark_str, $gray_basic);
            $watermark_x += 150;
          }
          $watermark_y += 50;
        }
        imagejpeg($img_basic, $filename_basic, $jpeg_quality); // Save the file

        // Create the thumbnail image - resize but no watermark required
        $thumb_ratio = $thumb_max_dim / $hires_max_dim;
        $thumb_w = $hires_w * $thumb_ratio;
        $thumb_h = $hires_h * $thumb_ratio;
        $thumb_x_offset = round(($thumb_max_dim - $thumb_w) / 2);
        $thumb_y_offset = round(($thumb_max_dim - $thumb_h) / 2);
        $img_thumb = imagecreatetruecolor($thumb_max_dim, $thumb_max_dim);
        $white_thumb = imagecolorallocate($img_thumb, 0xFF, 0xFF, 0xFF);
        imagefill($img_thumb, 0, 0, $white_thumb);
        imagecopyresampled($img_thumb, $img_hires,
                           $thumb_x_offset, $thumb_y_offset,
                           $hires_x_offset, $hires_y_offset,
                           $thumb_w, $thumb_h,
                           $hires_w, $hires_h);
        imagejpeg($img_thumb, $filename_thumb, $jpeg_quality); // Save the file

        // Free memory
        imagedestroy($img_basic);
        imagedestroy($img_thumb);
        imagedestroy($img_hires);

        // Add image to database and its tag association
        $query = "INSERT INTO $tblCartoons " .
                 "       (id,     description,             filename, upload_date, hidden, deleted, deleted_date, is_bestof)" .
                 "VALUES (NULL, '$description', '$new_base_filename',      NOW(),     '0',     '0'       , NULL,       '0')";
        $qresult = mysql_query($query); // SAFE: $description: escaped above
                                        //       $new_base_filename: locally generated
                                        //       other arguments are constant
        if ($qresult) {
          $cartoon_id = mysql_insert_id();
          $query = "INSERT INTO $tblTagMap (cartoon_id, tag_id) VALUES ('$cartoon_id', '$tag_id')";
          $qresult = mysql_query($query); // SAFE: $cartoon_id: locally generated
                                          //       $tag_id: verifiedabove
          if ($qresult) {
            $_SESSION["UPLOADED_FILES"][$orig_filename] = "Succeeded";
          }
          else {
            array_push($_SESSION["ERRORS"], "Database error setting tag: " . mysql_error());
            break;
          }
        }
        else {
          array_push($_SESSION["ERRORS"], "Database error adding image: " . mysql_error());
          break;
        }
      }
      else {
        unlink($filename_hires);
        array_push($_SESSION["ERRORS"], "Error reading $orig_filename: not a valid JPEG image");
        break;
      }
    }
    else {
      array_push($_SESSION["ERRORS"], "Error copying: $php_errormsg");
      break;
    }
  }

  if ($_SESSION["ERRORS"]) {
    header("Location: error.php");
  }
  else {
    header("Location: upload_complete.php");
  }
?>

    
Download this file
Jeremy Holland - Code Portfolio
Contact Me