how to keep image path on on input when other fields fails validation??

Discussion in 'PHP' started by macaela, Dec 6, 2012.

  1. #1
    Hi I have this script that validate 3 fields name dogsize and image, the problem is when I add image and leave the other fields empty I get the validation error of the other fields but then removes the image field even thou I've add already selected image.

    how can I keep the image field if other fields fail. so I dont hav eto add again?

    here the full script you can run it by not filling all the fields and you will see what i mean
    <?php
         include "connection.php"; // find file (connection.php)  
     $message = ""; // this variable starts empty then bellow it will be given variables depend on the error message
     $error_name = "";
     $error_dogsize = "";
    if (isset ($_POST["submit"])) { // if post has been set/clicked run the code below
    
    $first_name = mysql_real_escape_string($_POST['first_name']);
    $dogsize = mysql_real_escape_string($_POST['dogsize']);
    
    // start validate name
      if (empty($first_name)) // if name is empty
    	{
    		$error_name ='Please enter name';
    	}	
    	 else if(!preg_match("#^[-A-Za-z' ]*$#",$first_name)) { // name can only contain letter
    		$error_name ='Name must contain letter only';
    	}
    	
    	  if (empty($dogsize)) // if dogSize is empty
    	{
    		$error_dogsize ='Please select size of the dog';
    	}	
    
    	
    // end validation name   
       
    /*START IMAGE VALIDATION */
       // Configuration - Your Options
          $name = $_FILES['userfile']['name']; // get the name of the file
          $type = $_FILES['userfile']['type']; // get the type of the file
          $size = $_FILES['userfile']['size']; // get the size of the file
          
          $allowed = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
          $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
          $upload_path = './images/'; // The place the files will be uploaded to (currently a 'files' directory).
       		
       		$ext = substr($name, strpos($name,'.'), strlen($name)-1); // Get the extension from the filename.
         
         $fileType = in_array($ext, $allowed); // add the files type inside array filetype
    	 
       // Check if the filetype is allowed, if not DIE and inform the user.
       if(!$fileType) :
          $message = '<br />The file you attempted to upload is not allowed.';
       endif;
       
       // Now check the filesize, if it is too large then DIE and inform the user.
        if($size > $max_filesize) :
           $message = 'The file you attempted to upload is too large.';
       endif;
     
         $upload = is_writable($upload_path);
       // Check if we can upload to the specified path, if not DIE and inform the user.
       if(!$upload) :
            $message = 'You cannot upload to the specified directory, please CHMOD it to 777.';
       endif; 
    	  
        $filename = time().$ext; // this will give the file current time so avoid files having the same name
       
       // if file type is less than maximum amount and file is uploaded and the error name error variable is empty run the code
    	if($fileType && $size < $max_filesize && $upload && $error_name == "" && $error_dogsize == "") 
    		{ 
      			// Upload the file to your specified path.
    			if(move_uploaded_file($_FILES["userfile"]["tmp_name"],$upload_path . $filename))
    /* END IMAGE VALIDATION */
    				{
       // insert value into the database
    					$query = "INSERT INTO animals (id, first_name, dogsize,  image)  
                       			VALUES ('', '$first_name', '$dogsize',  '$filename')";
                        mysql_query($query) or
                        die (mysql_error()); 
       
    					echo time(). ' Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>'; 
    	 				$current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    					header ('Location: ' . $current_url);
    					exit ();
    			 		// It worked.
    				}
    		}
      //    else
       //      echo 'There was an error during the file upload.  Please try again.'; // It failed :(.
    //http://stackoverflow.com/questions/2666882/how-to-avoid-resending-data-on-refresh-in-php
    
    //scape string http://stackoverflow.com/questions/13034868/form-to-insert-data-in-database-works-but-does-not-show-success-page
    		 
    }
    
    ?>
    
    <form name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post">
    <h2>Upload an image</h2>
    <?php echo $error_name .'<br />';  ?>
    What is your name?<br>
    <input type="text" name="first_name" maxlength="50" value="<?php if (isset($first_name)) { echo $first_name;} ?>" /><br />
    <br />
    <?php echo $error_dogsize .'<br />';  ?>
    
    Select dog size:
    <select name="dogsize" id="dogsize">
      <option value="">Select</option>
      <option value="large">Large</option>
      <option value="medium">Medium</option>
      <option value="small">Small</option>
    </select>
    <br />
    <?php echo $message.'<br />';  ?>
    Upload an image: <br /><INPUT type="file" name="userfile" value="<?php if (isset($userfile)) { echo $userfile;} ?>"> 
    <br />
    <input type="submit" name="submit" value="Submit">
    </form>
    
    PHP:

     
    macaela, Dec 6, 2012 IP
  2. macaela

    macaela Active Member

    Messages:
    181
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #2
    in case anyone want to see the form here
    http://adoptadog.eurico.co.uk/index.php
    add image but leave the fields empty, it will remove the image when ask to fill other fields, how do I keep the image field
     
    macaela, Dec 7, 2012 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    I suspect you're completely misunderstanding how INPUTs of type="file" work -- the local filename is NEVER sent to the server, so there is NO 'real' way to repopulate it; and to be frank, you don't WANT to do what you are thinking on doing because it would be a MASSIVE waste of bandwidth.

    When a multi-part form is submitted, any files are uploaded -- that's what is sent to the server, the FILE, not the local path to it... The server has no access to the client (browser/visitors) hard drive; for good reason. If you repopulate that field with the file path again, that file is going to get uploaded again - massive waste of time and bandwidth.

    There are two ways of handling what I think you should be doing, the first should ALWAYS be done as it will always work, the latter relies on javascript and can be added atop your page to make it more convenient to the user. (though that's somewhat debatable depending on form complexity and how much scripting it takes).

    The first thing you should do is if the form values don't pass your validation, copy the image to a holding directory (since it is purged when the handling script ends) and change the form to list the image that's already been uploaded instead of showing a file input. A hidden field saying "already uploaded" or some such would then tell the handler to use that copy instead of a newly uploaded file on the resubmit.

    The second thing to do -- which is optional -- is to add a javascript layer of validation of inputs before ANYTHING is submitted, so you don't have to receive invalid data and then send the invalid data back to them.

    You should ALWAYS have the first as user input is ALWAYS suspect, scripting can be disabled, it can be unavailable -- and it can even be manipulated to do things you might not have wanted that form to do... so ALWAYS have code server side to handle when scripting is off. Good scripting then ENHANCES that functionality, instead of replacing it.

    But the bottom line is that you do NOT get the local/client path server-side -- so what you are asking for cannot be done, and because doing so would resend the same file wasting bandwidth, it shouldn't EVER be done either. Save a copy the first time they send, and change the form to reflect that they already sent an image.

    You might also want to set up something to purge old images should users say "shtup it" and not bother resending proper values.
     
    deathshadow, Dec 7, 2012 IP