Jump to content

Can somebody help me make my single file upload script into a multiple one?


Stevis2002

Recommended Posts

I know it needs a for loop, but i don't know where in the code i should be putting it?

 

function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
  {
  $value = stripslashes($value);
  }
// Quote if not a number
if (!is_numeric($value))
  {
  $value = "'" . mysql_real_escape_string($value) . "'";
  }
return $value;
}

$_POST = array_map('check_input', $_POST);

$sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images)
VALUES
({$_POST['customername']}, {$_POST['town']}, {$_POST['testimonial']}, {$_POST['sort_order']}, '$imgname'

)";

}
if (!mysql_query($sql,$con))
  {
  die("<br>Query: $sql<br>Error: " . mysql_error() . '<br>');
  }
echo "<p align=center><b>1 testimonial added</b></p>";

mysql_close($con);

 

Thanks in Advance,

Steve

Link to comment
Share on other sites

What do you want exactly ? And please use

<?php ?>

 

Sorry about the lack of php but i want to turn my section of script shown into one which will process multiple files uploaded.

At the moment, it uploads 1 file to server and sends the url into the db, but i don't know where i should be putting the loop to process 5 upload fields, and be able to choose whether or not to upload 2 files or 5 files?

Link to comment
Share on other sites

This is your loop,

 

The rest is up to you....

 

<?php

// Pick the amount
$UploadAmount = $_POST['amount'];

function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
  {
  $value = stripslashes($value);
  }
// Quote if not a number
if (!is_numeric($value))
  {
  $value = "'" . mysql_real_escape_string($value) . "'";
  }
return $value;
}

$_POST = array_map('check_input', $_POST);

// This is your loop, will run een x amount of time, depending on $UploadAmount
for ($x = 0; $x < $UploadAmount; $x++)
{
$sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images)
VALUES
({$_POST['customername']}, {$_POST['town']}, {$_POST['testimonial']}, {$_POST['sort_order']}, '$imgname'

)";
}

}
if (!mysql_query($sql,$con))
  {
  die("<br>Query: $sql<br>Error: " . mysql_error() . '<br>');
  }
echo "<p align=center><b>1 testimonial added</b></p>";

mysql_close($con);
?>

Link to comment
Share on other sites

This is your loop,

 

The rest is up to you....

 

<?php

// Pick the amount
$UploadAmount = $_POST['amount'];

function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
  {
  $value = stripslashes($value);
  }
// Quote if not a number
if (!is_numeric($value))
  {
  $value = "'" . mysql_real_escape_string($value) . "'";
  }
return $value;
}

$_POST = array_map('check_input', $_POST);

// This is your loop, will run een x amount of time, depending on $UploadAmount
for ($x = 0; $x < $UploadAmount; $x++)
{
$sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images)
VALUES
({$_POST['customername']}, {$_POST['town']}, {$_POST['testimonial']}, {$_POST['sort_order']}, '$imgname'

)";
}

}
if (!mysql_query($sql,$con))
  {
  die("<br>Query: $sql<br>Error: " . mysql_error() . '<br>');
  }
echo "<p align=center><b>1 testimonial added</b></p>";

mysql_close($con);
?>

 

Many Thanks for that, but i don't want the user to type in an amount, (i'm guessing that's what the array is for?), i just want to show 5 upload fields, and then the user to fill them with files to upload, but i want the script to upload them even if only 4 of the fields are used.

Link to comment
Share on other sites

Then you should create some count on the fields..... And change $UploadAmount to that amount. You can create a simple counter if you set the name fileds like

<input type="file" name="files[]" />

 

Then count the total amount like

$UploadAmount = count($_POST['files']);

Link to comment
Share on other sites

Your first step will be to define how you are going to store multiple upload images and associate them with the correct information in your database. Once you have done that, the code to loop over the uploaded files, which someone already posted a link to in your existing thread you have for this problem, is the simple part of what you need to do.

Link to comment
Share on other sites

Then you should create some count on the fields..... And change $UploadAmount to that amount. You can create a simple counter if you set the name fileds like

<input type="file" name="files[]" value="" />

 

Then count the total amount like

$UploadAmount = count($_POST['files']);

 

Ah, Thanks...so i would change

    <label for="images">Upload Image</label>
    <input type="file" name="images" id="images" />
    <input type="hidden" name="MAX_FILE_SIZE" value="500000" />

to

    <label for="images">Upload Image</label>
    <input type="file" name="images[]" id="images" />
    <input type="hidden" name="MAX_FILE_SIZE" value="500000" />

 

and then use the loop like so..

 

<?php

// Pick the amount
$UploadAmount = $count($_POST['images']);

function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
  {
  $value = stripslashes($value);
  }
// Quote if not a number
if (!is_numeric($value))
  {
  $value = "'" . mysql_real_escape_string($value) . "'";
  }
return $value;
}

$_POST = array_map('check_input', $_POST);

// This is your loop, will run een x amount of time, depending on $UploadAmount
for ($x = 0; $x < $UploadAmount; $x++)
{
$sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images)
VALUES
({$_POST['customername']}, {$_POST['town']}, {$_POST['testimonial']}, {$_POST['sort_order']}, '$imgname'

)";
}

}
if (!mysql_query($sql,$con))
  {
  die("<br>Query: $sql<br>Error: " . mysql_error() . '<br>');
  }
echo "<p align=center><b>1 testimonial added</b></p>";

mysql_close($con);
?>

Link to comment
Share on other sites

Like that yes. It depens on the rest of your code and what exactly you want to do with it. But you are on the right road now :)

 

Ok, Many thanks for your help, now i just have to try and figure out how to make each image url go into the same database table. I think i will need to add ,'s into the table somehow.

 

Thanks again for help :)

Link to comment
Share on other sites

$_POST['images'] has nothing to do with uploaded files.

 

Stevis2002, in your last thread for this problem, YOUR code is closer to what you actually need then anything that has been posted in this thread. Why did you start a new thread and throw away all the information leading up to this point and why did you remove the existing code in your code that was getting the $_FILES information for the 1st file?

 

 

Link to comment
Share on other sites

$_POST['images'] has nothing to do with uploaded files.

 

 

Isn't the $_POST['images'] to do with getting how many image fields have been sent to the script to be uploaded....

 

like so...

  </p>
    <p align="center">
    <label for="images">Upload Image</label>
    <input type="file" name="images[]" id="images" />
    <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  </p>
    <p align="center">
    <label for="images">Upload Image</label>
    <input type="file" name="images[]" id="images" />
    <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  </p>
    <p align="center">
    <label for="images">Upload Image</label>
    <input type="file" name="images[]" id="images" />
    <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  </p>

Link to comment
Share on other sites

$_POST['images'] has nothing to do with uploaded files.

 

Stevis2002, in your last thread for this problem, YOUR code is closer to what you actually need then anything that has been posted in this thread. Why did you start a new thread and throw away all the information leading up to this point and why did you remove the existing code in your code that was getting the $_FILES information for the 1st file?

 

 

 

Because i got mega confused :(

Link to comment
Share on other sites

Ok,. so now i have placed the for loop in with the altered code and it has all gone kinda eggshaped

 

  </p>
  <p align="center">
    <label for="images">Upload Image</label>
   <input type="file" name="images[]" />
   <input type="file" name="images[]" />
   <input type="file" name="images[]" />
   <input type="file" name="images[]" />
   <input type="file" name="images[]" />
  </p>
  <p align="center">
    <input type="submit" name="submit" id="submit" value="Submit" />
  </p>
  <p> </p>
  <p> </p>
</form>
<p align="center"> </p>
</body>
<?php
$con = mysql_connect("localhost","xxxxxxxxxxxxxxxxxx","xxxxxxxxxxxx");

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 (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("xxxxx", $con);

$image_tmpname = $_FILES['images']['name'];
$imgdir = "uploaded_images/";
$imgname = $imgdir.$image_tmpname;

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

// Pick the amount
// $UploadAmount = $count($_POST['images'])

function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
  {
  $value = stripslashes($value);
  }
// Quote if not a number
if (!is_numeric($value))
  {
  $value = "'" . mysql_real_escape_string($value) . "'";
  }
return $value;
}

$_POST = array_map('check_input', $_POST);
// for ($x = 0; $x < $UploadAmount; $x++)
// {
$sql="INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, Images)
VALUES
({$_POST['customername']}, {$_POST['town']}, {$_POST['testimonial']}, {$_POST['sort_order']}, '$imgname')";
}
// }
if (!mysql_query($sql,$con))
  {
  die("<br>Query: $sql<br>Error: " . mysql_error() . '<br>');
  }
echo "<p align=center><b>1 testimonial added</b></p>";

mysql_close($con);
?>

Link to comment
Share on other sites

Have you done this yet -

Your first step will be to define how you are going to store multiple upload images and associate them with the correct information in your database.

 

Because it is simply impossible to write any code that does what you want unless you have defined what the end result is going to be.

Link to comment
Share on other sites

And I just noticed that the check_input() function is not ideal because it is adding part of the sql syntax onto the outside of the data, which means it will only work for the simplest queries, creates special conditions in your query syntax so that you must now use multiple different syntaxes for string data in your queries, and it does not work if any of your $_POST fields are arrays.

Link to comment
Share on other sites

The following sample code demonstrates how you might accomplish this (tested) -

 

<?php
// various configuration values used in the code
$required = array('customername'=>'Customer Name', 'town'=>'Town/City', 'testimonial'=>'Testimonial', 'sort_order'=>'Sort Order'); // 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()

// 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!';
}

// at this point, if there are no errors, the $_FILES and $_POST arrays contain something and can be processed
if(empty($errors)){
	include('dbinfo.php'); // get your database connection information
	// connect to db server and select db (assumes only this code requires a connection...)
	if($con = mysql_connect($db_host,$db_user,$db_pwd)){
		// connect worked
		if(!mysql_select_db($db_name, $con)){
			// select failed
			$errors[] = "A database error occurred that prevents this page from working at this time!";
			trigger_error('Could not select database: ' . mysql_error($con));
		}
	} else {
		// connect failed
		$errors[] = "A database error occurred that prevents this page from working at this time!";
		trigger_error('Could not connect: ' . mysql_error($con));
	}

	// database connect/select worked, proceed with validating the form data
	if(empty($errors)){
		// 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[$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)
					VALUES
					('%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'])
					);
				// execute query
				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:<br />";
	foreach($errors as $error){
		echo "$error<br />";
	}
}
} // 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'] : '';

?>
<form action="" method="post" enctype="multipart/form-data" name="add_test" id="add_test">
  <p> </p>
  <p align="center">
    <label for="customername">Customer Name:</label>
    <input name="customername" type="text" id="customername" maxlength="150" value="<?php echo $_POST['customername']; ?>" />
  </p>
  <p align="center">
    <label for="town">Town/City:   </label>
    <input name="town" type="text" id="town" maxlength="150" value="<?php echo $_POST['town']; ?>" />
  </p>
  <p align="center">
    <label for="testimonial"><u>Testimonial </u></label>
  </p>
  <p align="center">
    <textarea name="testimonial" id="testimonial" cols="60" rows="10"><?php echo $_POST['testimonial']; ?></textarea>
  </p>
  <p align="center">
    <label for="sort_order">Sort Order: </label>
    <input name="sort_order" type="text" id="sort_order" size="10" maxlength="3" value="<?php echo $_POST['sort_order']; ?>" />
  </p>
  <p align="center">
    <label for="images"><u>Upload Images</u></label>
</p>
  <p align="center">	
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" />
  </p>

  <p align="center">
    <input type="submit" name="submit" id="submit" value="Submit" />
  </p>
  <p> </p>
  <p> </p>
</form>

Link to comment
Share on other sites

Thanks for the help mate, but when i adjust and un thej script, it all goes fine, apart from nothing gets entered into the url field in the database, just NULL..

<?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;
}
?>
<!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>xxxxxxxxxxxxxxxxxxxxxx - Add Testimonial</title>
<link href="testimonials.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div align="center">
  <h1><strong>xxxxxxxxxxxxxxxxxxxx Administration Area</strong></h1>
</div>
<p align="center"> </p>
</body>
<?php
$con = mysql_connect("localhost","xxxxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxx");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("xxxxxxxxxxxx", $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()

// 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[$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
               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:<br />";
      foreach($errors as $error){
         echo "$error<br />";
      }
   }
// 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'] : '';

?>
<form action="" method="post" enctype="multipart/form-data" name="add_test" id="add_test">
  <p> </p>
  <p align="center">
    <label for="customername">Customer Name:</label>
    <input name="customername" type="text" id="customername" maxlength="150" value="<?php echo $_POST['customername']; ?>" />
  </p>
  <p align="center">
    <label for="town">Town/City:   </label>
    <input name="town" type="text" id="town" maxlength="150" value="<?php echo $_POST['town']; ?>" />
  </p>
  <p align="center">
    <label for="testimonial"><u>Testimonial </u></label>
  </p>
  <p align="center">
    <textarea name="testimonial" id="testimonial" cols="60" rows="10"><?php echo $_POST['testimonial']; ?></textarea>
  </p>
  <p align="center">
    <label for="sort_order">Sort Order: </label>
    <input name="sort_order" type="text" id="sort_order" size="10" maxlength="3" value="<?php echo $_POST['sort_order']; ?>" />
  </p>
  <p align="center">   
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" />
   <input type="hidden" name="MAX_FILE_SIZE" value="500000" />
  </p>

  <p align="center">
    <input type="submit" name="submit" id="submit" value="Submit" />
  </p>
  <p> </p>
  <p> </p>
</form>

 

Link to comment
Share on other sites

nothing gets entered into the url field in the database, just NULL..

 

That's because the code you put in does not have or set any value for that field in the database.

 

Someone has suggested twice in this thread that you need to define how you are going to store multiple images and associate them with the correct information in the database. The sample code I posted did associate the multiple files with the id in the database by including the id as part of the file name. If you want something different than that method, you will need to define it and then write the code to accomplish it.

Link to comment
Share on other sites

Thanks PFM,

 

I thought i was getting somewhere but now it throws up an internal 500 error.

I have an error saying in DW of a syntax error on line 283, but i cannot see anything wrong with the line or any line near it.

Can you see anything wrong now?

 

<?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;
}
?>
<!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>Admin Area - Add Testimonial</title>
<link href="testimonials.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div align="center">
  <h1><strong>Administration Area</strong></h1>
</div>
<p align="center"> </p>
</body>
<?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:<br />";
      foreach($errors as $error){
         echo "$error<br />";
      }
   }
// 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'] : '';


?>

<form action="" method="post" enctype="multipart/form-data" name="add_test" id="add_test">
  <p> </p>
  <p align="center">
    <label for="customername">Customer Name:</label>
    <input name="customername" type="text" id="customername" maxlength="150" value="<?php echo $_POST['customername']; ?>" />
  </p>
  <p align="center">
    <label for="town">Town/City:   </label>
    <input name="town" type="text" id="town" maxlength="150" value="<?php echo $_POST['town']; ?>" />
  </p>
  <p align="center">
    <label for="testimonial"><u>Testimonial </u></label>
  </p>
  <p align="center">
    <textarea name="testimonial" id="testimonial" cols="60" rows="10"><?php echo $_POST['testimonial']; ?></textarea>
  </p>
  <p align="center">
    <label for="sort_order">Sort Order: </label>
    <input name="sort_order" type="text" id="sort_order" size="10" maxlength="3" value="<?php echo $_POST['sort_order']; ?>" />
  </p>
  <p align="center">  
   <input type="hidden" name="MAX_FILE_SIZE" value="500000" /> 
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" /><br />
   <input type="file" name="images[]" />
  
  </p>

  <p align="center">
    <input type="submit" name="submit" id="submit" value="Submit" />
  </p>
  <p> </p>
  <p> </p>
</form> 
</html>

Link to comment
Share on other sites

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.