PDA

View Full Version : Php image upload help


Stevis2002
12-03-2010, 09:05 AM
Please can somebody help me with my script? It uploads everything fine, except it doesn't store the image urls in the database


<?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">&nbsp;</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>&nbsp;</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>&nbsp;</p>
<p>&nbsp;</p>
</form>


Thanks in Advance,
Steve

edbr
12-04-2010, 12:08 AM
the insert staement
// 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']),


dont see the image path

Stevis2002
12-04-2010, 07:34 AM
the insert staement
// 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']),


dont see the image path

Thanks for the help, but it is still not passing the information to the database.


$con = mysql_connect("localhost","xxxxxxxxxxxxxxx","xxxxxxxxxxxxxxxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("web168-nowaysis", $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>&nbsp;</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>&nbsp;</p>
<p>&nbsp;</p>
</form>

Stevis2002
12-05-2010, 07:03 PM
Anybody else able to help please?

edbr
12-06-2010, 01:49 AM
if you echo $_POST['images'] what value do you get?

Stevis2002
12-06-2010, 08:24 AM
if you echo $_POST['images'] what value do you get?


It says.....The following errors occurred:
Form field: Images, is empty!

Stevis2002
12-07-2010, 08:38 AM
It says.....The following errors occurred:
Form field: Images, is empty!

I cannot work out why it isn't passing data to the Image field which will store thej url, because it was before, but i don't know how to store more than 1 image name either

jmichae3
12-07-2010, 09:33 AM
your action attribute must have the path to your form processing PHP file.

jmichae3
12-07-2010, 09:42 AM
you might want to read this...
http://php.net/manual/en/features.file-upload.post-method.php

Stevis2002
12-07-2010, 11:59 AM
your action attribute must have the path to your form processing PHP file.

It does, because it is on the same page

jmichae3
12-08-2010, 05:17 AM
the insert should be performed probably *after* the files are moved I should think (it's your code, you should probably think that out). did you want the temp files or the resulting moved files?

the insert statement's $_POST['images'] is missing a subscript or two.

$_POST['images'] is an array, not a plain variable. that's why I wanted you to look at the structure of the print_r() results of the uploaded array that is returned by the form on that page.

when you do get it right, $_POST['images'] will contain an array of 4 of these:

Array
(
[name] => Array
(
[0] => facepalm.jpg
[1] =>
)

[type] => Array
(
[0] => image/jpeg
[1] =>
)

[tmp_name] => Array
(
[0] => /tmp/phpn3FmFr
[1] =>
)

[error] => Array
(
[0] => 0
[1] => 4
)

[size] => Array
(
[0] => 15476
[1] => 0
)
)


also, PHP.INI determines the maximum size of the upload look in the manual to see what those settings are. usually this is around 2MB. anything over that is an error or doesn't work. I've tried. I have had a hard time configuring PHP.INI to actually take anything over 2MB and actually work, but I am not an expert at php.ini.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field. that means it must come BEFORE the file input field. you have it after. this may be why you are having empty results.

Stevis2002
12-08-2010, 02:38 PM
Thanks for the help.

I thought i was getting somewhere but now i get a 500 internal server error, and an syntax error on line 283, which seems ok to me.


<?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">&nbsp;</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>&nbsp;</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>&nbsp;</p>
<p>&nbsp;</p>
</form>
</html>

bee80
12-09-2010, 07:06 AM
your action attribute must have the path to your form processing PHP file.

when its left blank it automatically send to itself PHP_SELF so its fine

Stevis2002
12-09-2010, 09:08 AM
Can anybody help me with this anymore please?

Stevis2002
12-12-2010, 06:36 AM
Can anybody help me with this anymore please?

I just need to get this upload bit working and then that is all the help i need then, so if anyone can help me finish it then it would be very much appreciated

Thanks all