Jump to content

Stevis2002

Members
  • Posts

    98
  • Joined

  • Last visited

    Never

Posts posted by Stevis2002

  1. Ok,

     

    So now i have altered the way i am dealing with images to try and make it easier for me to get working, but it is not uploading file to server, or file info to db.

    I have made the extra db fields, pic1, pic2 etc, but nothing is getting there

     

    if(isset($_POST['submit']))  
    
    {  
    
    $customername = $_POST['customername'];  
    $imagename = $_POST['imagename'];  
    $testimonial = $_POST['testimonial']; 
    $sort_order = $_POST['sortorder'];
    $town = $_POST['town'];
    
    $uploaddir = 'uploaded_images/';  
    
    $uploadfile = $uploaddir . basename($_FILES['ipic1']['imagename']);  
        
    
    echo($_FILES['ipic1']['type']);  
       
    move_uploaded_file($_FILES['ipic1']['tmp_name'], $uploadfile);     
    
    $pic1 = $_FILES['ipic1']['imagename'];  
    
    
    $uploaddir2 = 'uploaded_images/';  
    
    $uploadfile2 = $uploaddir2 . basename($_FILES['ipic2']['imagename']);  
         
    
    echo($_FILES['ipic2']['type']);  
    
    
    move_uploaded_file($_FILES['ipic2']['tmp_name'], $uploadfile2);  
       
    
    $pic2 = $_FILES['ipic2']['imagename'];  
    
    
    $uploaddir3 = 'uploaded_images/';  
    
    $uploadfile3 = $uploaddir3 . basename($_FILES['ipic3']['imagename']);  
       
    
    echo($_FILES['ipic3']['type']);  
    
      
    
    move_uploaded_file($_FILES['ipic3']['tmp_name'], $uploadfile3);  
    
      
    
    $pic3 = $_FILES['ipic3']['imagename'];  
    
    
    $uploaddir4 = 'uploaded_images/';  
    
    $uploadfile4 = $uploaddir4 . basename($_FILES['ipic4']['imagename']);  
      
    
    echo($_FILES['ipic4']['type']);  
    
       
    
    move_uploaded_file($_FILES['ipic4']['tmp_name'], $uploadfile4);  
       
    $pic4 = $_FILES['ipic4']['imagename'];  
    
    $uploaddir5 = 'uploaded_images/';  
    
    $uploadfile5 = $uploaddir5 . basename($_FILES['ipic5']['imagename']);  
      
    
    echo($_FILES['ipic5']['type']);  
    
       
    
    move_uploaded_file($_FILES['ipic5']['tmp_name'], $uploadfile5);  
       
    $pic5 = $_FILES['ipic5']['imagename']; 
       
                   $query=sprintf("INSERT INTO testimonials (CustomerName, Town, Testimonial, SortOrder, pic1, pic2, pic3, pic4, pic5)
                      VALUES
                      ('$customername','$town','&testimonial','$sort_order','$pic1','$pic2','$pic3','$pic4','$pic5')",
                      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['pic1']),
    			  mysql_real_escape_string($_POST['pic2']),
    			  mysql_real_escape_string($_POST['pic3']),
    			  mysql_real_escape_string($_POST['pic4']),
    			  mysql_real_escape_string($_POST['pic5'])
                      );
    
    mysql_query($query) or die('Error, insert query failed, could not connect to database');  
    
    
    
    echo "New testimonial added  \n";  
    
    
    }  
    
    ?> 
    
    
    <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="ipic1" /><br />
       <input type="file" name="ipic2" /><br />
       <input type="file" name="ipic3" /><br />
       <input type="file" name="ipic4" /><br />
       <input type="file" name="ipic5" />
      </p>
    
      <p align="center">
        <input type="submit" name="submit" id="submit" value="Submit" />
      </p>
      <p> </p>
      <p> </p>
    </form> 
    </html>
    

  2. 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.

    Hi mate,

     

    How much would you charge just to finish this script off for me so it uploads multiple images, and stores url&image info in db?

     

    I think i will be able to manage to get the info back out ok and disply the image(s)

     

    Cheers,

    Steve

     

    Aimed at PFMaBiSmAd  BTW lol

  3. 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.

    Hi mate,

     

    How much would you charge just to finish this script off for me so it uploads multiple images, and stores url&image info in db?

     

    I think i will be able to manage to get the info back out ok and disply the image(s)

     

    Cheers,

    Steve

  4. 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>

  5. 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>

     

  6. 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);
    ?>

  7. $_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 :(

  8. $_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>

  9. 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);
    ?>

  10. 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.

  11. 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?

  12. 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

×
×
  • 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.