Help with multiple image uploads script

Hi all,m

Please can anybody help me with this script?

I want it to enter information into the database from the form, which will include the url of the images into the db table field called ímages.
It also uploads the file to the server, but i cannot get it to work.

Cheers,
Steve

[php]

<?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 = "index.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 = "index.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($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) $MM_referrer .= "?" . $_SERVER['QUERY_STRING']; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> Admin Area - Add Testimonial

Administration Area

 

<?php $con = mysql_connect("localhost","xxxxxxxx","xxxxxxxxxxxxx"); if (!$con) { die('Could not connect: ' . mysql_error()); }

mysql_select_db(“xxxxxxxxxxxxxxxxxx”, $con);

// various configuration values used in the code
$required = array(‘customername’=>‘Customer Name’, ‘town’=>‘Town/City’, ‘testimonial’=>‘Testimonial’, ‘sort_order’=>‘Sort Order’, ‘images’=>‘Images’); // required form field names and labels (used in validation logic)
$upload_name = ‘images’; // the name of the upload field(s) $_FILES[‘images’]
$imgdir = “uploaded_images/”; // destination folder
$image_types = array(IMG_GIF,IMG_JPG,IMG_PNG); // acceptable types returned by getimagesize()
$image_tmpname = $_FILES[‘images’][‘name’];
$imgname = $imgdir.$image_tmpname;

// form processing starts here - check if a form submitted to this code
if($_SERVER[‘REQUEST_METHOD’] == ‘POST’){
$errors = array(); // store any errors
// check if the $_FILES array contains anything
// the following two if() tests assume that the form will always set at least one $_POST field ($_POST[‘submit’])
if(empty($_FILES) && !empty($_POST)){
// no $_FILES information but there is $_POST information
$errors[] = ‘No uploaded file information, either the form is invalid (no enctype or no file fields) or uploads are not enabled on this server!’;
}
if(empty($_FILES) && empty($_POST)){
// both are empty, the maximum post size was exceeded
$errors[] = ‘No uploaded file information, the total size of all post data and uploaded files exceeds the post_max_size setting!’;
}

// validate the form data (customername, town, testimonial, sort_order, and at least one image are required)
foreach($required as $key=>$value){
// isset($_POST[$key]) && $_POST[$key] != ‘’ complemented gives -> !isset($_POST[$key]) || $_POST[$key] == ‘’
if(!isset($_POST[$key]) || $_POST[$key] == ‘’){
$errors[] = “Form field: $value, is empty!”;
}
}
// add other validation tests here …

     // validate the uploaded file(s), must be at least one that is of type gif, jpg, or png
     $upload_errors = array(UPLOAD_ERR_OK => 'There is no error, the file uploaded with success.',
                       UPLOAD_ERR_INI_SIZE => 'The file exceeds the upload_max_filesize directive!',
                       UPLOAD_ERR_FORM_SIZE => 'The file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form!',
                       UPLOAD_ERR_PARTIAL => 'The file was only partially uploaded!',
                       UPLOAD_ERR_NO_FILE => 'No file was uploaded!',
                       UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder!',
                       UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk!',
                       UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload!');

     $num_images = 0; // count the number of valid images
	 
	 foreach ($_FILES["images"]["error"] as $key => $error) {    if ($error == UPLOAD_ERR_OK) {        $tmp_name = $_FILES["images"]["tmp_name"][$key];        $name = $_FILES["images"]["name"][$key];        move_uploaded_file($tmp_name, "data/$name");    }}

	 if(move_uploaded_file($_FILES['images']['tmp_name'], $imgname)){list($width,$height,$type,$attr)= getimagesize($imgname);
	 switch($type){ 
	 case 1:  $ext = ".gif"; break;
	  case 2:  $ext = ".jpg"; break;
	   case 3:  $ext = ".png"; break; default:
	      echo "Not acceptable format of image";}
	 
     foreach ($_FILES[$upload_name]["error"] as $key => $error){
        if ($error == UPLOAD_ERR_OK){
           // a file was successfully uploaded, check if an image and get the image data from it
           if(list($width,$height,$type,$attr)= getimagesize($_FILES[$upload_name]["tmp_name"][$key])){
              // is an image, count it if it is allowed type
              if(in_array($type,$image_types)){
                 $num_images++;
              } else {
                 // wrong image type
                 $errors[] = "The uploaded file: {$_FILES[$upload_name]["name"][$key]}, is not a gif, jpg, or png type!";
              }
           } else {
              // not an image
              $errors[] = "The uploaded file: {$_FILES[$upload_name]["name"][$key]}, is not an image file!";
           }
        } else {
           // upload error occurred. If error = 4, file form field was left empty and ignore the error
           if($error != 4){
              $ul_error_message = isset($upload_errors[$error]) ? $upload_errors[$error] : "An unknown error";
              $errors[] = "The uploaded file: {$_FILES[$upload_name]["name"][$key]}, failed because: $ul_error_message!";
           }
		}
     } // end foreach
     if(!$num_images){
        $errors[] = "No valid images were uploaded, you must upload one or more images!";
     }

     // Expected $_POST and $_FILES data exists, process the actual data
     if(empty($errors)){
        // verify the destination directory
        if(!is_dir($imgdir)){
           $errors[] = "The upload destination directory: $imgdir, does not exist";
        } else {
           // directory does exist, check permissions
           if(!is_writable($imgdir)){
              $errors[] = "The upload destination directory: $imgdir, is not writable!";
           }
        }
        
        // destination directory exists and is writable
        if(empty($errors)){
           $query=sprintf("INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images)
              VALUES
              ('%s','%s','%s','%s','%s')",
              mysql_real_escape_string($_POST['customername']),
              mysql_real_escape_string($_POST['town']),
              mysql_real_escape_string($_POST['testimonial']),
              mysql_real_escape_string($_POST['sort_order']),
      mysql_real_escape_string($_POST['images'])
              );
           // execute query
		   echo $_POST['images'];
           if (!mysql_query($query,$con)){
              // query failed
              $errors[] = "The submitted data could not be inserted into the database due to a fatal error!";
              trigger_error("Query: $query, failed: " . mysql_error($con));
           } else {
              // query executed without error
              if(mysql_affected_rows($con)){
                 // row was inserted, get the id
                 $last_id = sprintf("%05d",mysql_insert_id($con)); // get the id just used, pad to 6 places
                 // move the uploaded files to the final destination
                 // prepend the $last_id onto each file name to create unique names and to associate the files with the record in the database table
                 // loop over files (again) processing valid images
                 foreach ($_FILES[$upload_name]["error"] as $key => $error){
                    if ($error == UPLOAD_ERR_OK){
                       // a file was successfully uploaded, check if an image and get the image data from it
                       if(list($width,$height,$type,$attr)= getimagesize($_FILES[$upload_name]["tmp_name"][$key])){
                          // is an image, process it if it is allowed type
                          if(in_array($type,$image_types)){
                             // is an allowed image type
                             $tmp_name = $_FILES[$upload_name]["tmp_name"][$key];
                             $name = $_FILES[$upload_name]["name"][$key];
                             $whole_name = $last_id . '_' . $name;
                             if(!move_uploaded_file($tmp_name, "$imgdir$whole_name")){
                                $errors[] = "The uploaded file: $name, could not be saved to: $imgdir$whole_name!";
                             } else {
                                echo "The uploaded file: $name, was saved to: $imgdir$whole_name<br />";
                             }
                          }
                       }
                    }
                 } // end foreach
                 echo "<p align=center><b>1 testimonial added</b></p>";
              } else {
                 // query failed to insert row
                 // the only way this branch can be reached is if the query executed without error but the row was not inserted
                 $errors[] = "The submitted data could not be inserted into the database due to a fatal error!";
                 trigger_error("Query: $sql, failed: " . mysql_error($con));                  
              }
           }
        } // end of verify destination directory
     } // end of process the actual data
     mysql_close($con);
  } // end of validating form data

// end of $_FILES/$_POST arrays contain data
// display any errors that occurred during the processing of the form
if(!empty($errors)){
echo “The following errors occurred:
”;
foreach($errors as $error){
echo “$error
”;
}
}
// end of request_method check

// display the form (always)
// if post values don’t exist, give them default values here (doing this before the upload test would give incorrect results) to be used in the value="" attributes
$_POST[‘customername’] = isset($_POST[‘customername’]) ? $_POST[‘customername’] : ‘’;
$_POST[‘town’] = isset($_POST[‘town’]) ? $_POST[‘town’] : ‘’;
$_POST[‘testimonial’] = isset($_POST[‘testimonial’]) ? $_POST[‘testimonial’] : ‘’;
$_POST[‘sort_order’] = isset($_POST[‘sort_order’]) ? $_POST[‘sort_order’] : ‘’;
$_POST[‘images’] = isset($_POST[‘images’]) ? $_POST[‘images’] : ‘’;

?>

 

Customer Name:

Town/City:

Testimonial

<?php echo $_POST['testimonial']; ?>

Sort Order:





 

 

[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service