Jump to content

Quick Question: Form Validation (Newbish)


webmaster1

Recommended Posts

Hi Freaks!  ;D

 

I've just finished building a form consisting of text and file input fields. I have a second file that the form is posted to that sends the input to a mySQL database.

 

I've fished around Google but I don't know whether to use CLIENT SIDE (javascript) or SERVER SIDE (php). What I do know is that I want the validation to occur on the form page BEFORE THE FORM ACTUALLY POSTS and I don't want to use alert boxes either.

 

Can anybody show me a quick example of the mechanics of form validation error messages based on the below form and included comments:

 

 

<?php
//check that just this field isn't empty
<input name="ufile[]" type="file" id="ufile[]" size="50" /></br>

//check that none of the next three fields are empty
<input name="ufile[]" type="file" id="ufile[]" size="50" /></br>
<input name="ufile[]" type="file" id="ufile[]" size="50" /></br>
<input name="ufile[]" type="file" id="ufile[]" size="50" /></br>

//check that value is numeric and contains only four digits but no comma or euro symbol
<input type="text" name="number" id="number" class="text"></br>

//check that value contains letters only
<input type="text" name="letter" id="letter" class="text"></br>

?>

 

I'm not sure when or how to use striplashes, empty or isset. The above form is just an example based on what I need to know.

 

A useful link might also suffice.

Link to comment
Share on other sites

Here is a simple way to do validation:

 

<?php

if ($_POST) {
// validate fields
if (count($_FILES['ufile']) < 4) {
	$errors['ufile'] = 'Error: blah blah blah';
}
if (!is_numeric($_POST['number']) or strlen($_POST['number']) != 4) {
	$errors['number'] = 'Error: blah blah blah';
}
if (!preg_match('/^[\w]*$/',$_POST['letter'])) {
	$errors['letter'] = 'Error: blah blah blah';
}

if (empty($errors)) {
	// there were no errors, do whatever you want to do here
}
}

?>

//check that just this field isn't empty
<?php echo ($errors['ufile']) ? '<div class="error">'.$errors['ufile'].'</div>' : '' ?>
<input name="ufile[]" type="file" id="ufile[]" size="50" /><br />

//check that none of the next three fields are empty
<input name="ufile[]" type="file" id="ufile[]" size="50" /><br />
<input name="ufile[]" type="file" id="ufile[]" size="50" /><br />
<input name="ufile[]" type="file" id="ufile[]" size="50" /><br /

//check that value is numeric and contains only four digits but no comma or euro symbol
<?php echo ($errors['number']) ? '<div class="error">'.$errors['number'].'</div>' : '' ?>
<input type="text" name="number" id="number" class="text"><br />

//check that value contains letters only
<?php echo ($errors['letter']) ? '<div class="error">'.$errors['letter'].'</div>' : '' ?>
<input type="text" name="letter" id="letter" class="text"><br />

Link to comment
Share on other sites

That exactly what I was looking to do. Its great the way the error messages pop up in a relevant spot too.

 

Just two more questions on the below lines of code:

 

if ($_POST)

 

Does this mean 'when the submit button is clicked and the form is posting'?

 

if (empty($errors)) 

 

What exactly would I do here? I'm not sure I understand what the action is. Do I need to add additional code here to make my form post or would I just put a message in like "No errors were found"?

 

Link to comment
Share on other sites

if ($_POST)

 

Checks to see if the form was posted.  It would be better to do something like this:

 

if ($_POST['name_of_submit_button'] == 'Submit')

 

if (empty($errors)) 

 

And here is where I would actually insert the data into a database and move the uploaded files to wherever you plan to store them.  Whenever you are done with the database and file upload stuff, you can either redirect to a success page or just display a success message on the same page as the form.

Link to comment
Share on other sites

:) So after the if (empty($errors)) I can just paste in all the code I thought I had to have in a  seperate page?

 

Here's my code to process the form by the way. I know its probably messy but I'm very proud of it (newbishly of course).

 


<?php

//FIRST CHECK FILE TYPE BUT NOT SIZE

if (

     (
     //BEGIN IMAGE FILE 1
     (
     ($HTTP_POST_FILES['ufile']["type"][0] == "image/gif")
     || ($HTTP_POST_FILES['ufile']["type"][0] == "image/jpeg")
     || ($HTTP_POST_FILES['ufile']["type"][0] == "image/pjpeg")
      )
     //&&($HTTP_POST_FILES['ufile']["size"][0] < 50000)
     //END IMAGE FILE 1
     )

     &&

     (
     //BEGIN IMAGE FILE 2
     (
     ($HTTP_POST_FILES['ufile']["type"][1] == "image/gif")
     || ($HTTP_POST_FILES['ufile']["type"][1] == "image/jpeg")
     || ($HTTP_POST_FILES['ufile']["type"][1] == "image/pjpeg")
     )
     //&&($HTTP_POST_FILES['ufile']["size"][1] < 50000)
     //END IMAGE FILE 2
     )

     &&

     (
     //BEGIN IMAGE FILE 3
     (
     ($HTTP_POST_FILES['ufile']["type"][2] == "image/gif")
     || ($HTTP_POST_FILES['ufile']["type"][2] == "image/jpeg")
     || ($HTTP_POST_FILES['ufile']["type"][2] == "image/pjpeg")
     )
     //&&($HTTP_POST_FILES['ufile']["size"][2] < 50000)
     //END IMAGE FILE 3
     )

)


{

//DEFINE PATHS AS VARIABLES

$path1= "upload/".$HTTP_POST_FILES['ufile']['name'][0];
$path2= "upload/".$HTTP_POST_FILES['ufile']['name'][1];
$path3= "upload/".$HTTP_POST_FILES['ufile']['name'][2];

//NEXT CHECK IF EITHER OF THE FILES ALREADY EXIST

if (file_exists($path1) || file_exists($path2) || file_exists($path3))
     
     {
     echo "<b>ERROR</b></br></br>
     None of the selected image files have been uploaded as a result of either or both of the following incidents occurring:</br></br>
     1) The requisite amount of files have not been uploaded (three images minimum / maximum).</br>
     2) One or more of the image files you attempted to upload already exist on the server. 
     Please ensure that you have not already uploaded the image file(s) and / or that each file name is unique.</br></br>
     Tip: Try naming the image files semantically after a combination of the make, model and year of the vehichle rather than a random series of letters and numbers.
     </br></br>
     Should you experience further technical difficulty please contact the web master:</br></br>
     [place button here to link to web master cms error log form]
     ";
     }


//NEXT POST THE IMAGES TO THE DESIGNATED FOLDER ON THE SERVER

else {

copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);
copy($HTTP_POST_FILES['ufile']['tmp_name'][1], $path2);
copy($HTTP_POST_FILES['ufile']['tmp_name'][2], $path3);

//PICK UP THE VARIABLES FROM THE TEXT FIELDS

        //$imgurl1 = "upload/" . $_FILES["file"]["name"];
        $make = $_POST['make'];
        $model = $_POST['model'];
        $price = $_POST['price'];
        $engine = $_POST['engine'];
        $body = $_POST['body'];
        $transmission = $_POST['transmission'];
        $year = $_POST['year'];
        $colour = $_POST['colour'];
        $mileagem = $_POST['mileagem'];
        $mileagekm = $_POST['mileagekm'];
        $owners = $_POST['owners'];
        $doors = $_POST['doors'];
        $location = $_POST['location'];
        $info = $_POST['info'];

//DEFINE ADDITIONAL VARIABLES

        $now_datetime = date('Y-m-d h:i:s');
        $ipaddress = getenv('REMOTE_ADDR');

//NOW CONNECT TO DATABASE

include("dbinfo.php");
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to establish a connection to database.");

// INSERT INTO DATABASE

       // Insert into database
$query = "INSERT INTO test VALUES ('','$make','$model','$price','$engine','$body','$transmission','$year','$colour','$mileagem','$mileagekm','$owners','$doors','$location','$info','$now_datetime','$ipaddress','$path1','$path2','$path3')";
mysql_query($query);

//NEXT DISPLAY A SUMMARY OF WHAT HAS BEEN UPLOADED


echo "This item has been successfully submitted to the server.</br></br>
The following image file have been appended to your uploaded:</br></br>
";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>"; 
//echo "File Size :".$HTTP_POST_FILES['ufile']['size'][0]." KB<BR/>"; 
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>"; 
//echo "<img src=\"$path1\" height=\"150\">";
echo "<P>";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][1]."<BR/>"; 
//echo "File Size :".$HTTP_POST_FILES['ufile']['size'][1]."<BR/>"; 
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][1]."<BR/>"; 
//echo "<img src=\"$path2\" height=\"150\">";
echo "<P>";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][2]."<BR/>"; 
//echo "File Size :".$HTTP_POST_FILES['ufile']['size'][2]."<BR/>"; 
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][2]."<BR/>"; 
//echo "<img src=\"$path3\" height=\"150\">";

echo "</br>It's best practice to confirm that your item has been submitted as desired</br></br>
[place button here to link to view relevant section]</br></br>
If you notice an error as a result of human input please find and delete the item indefinitely and reattempt its submission. 
Itens should also be deleted as soon as they become redundant (e.g. vehichle sold)</br></br>
Should you experience further technical difficulty please contact the web master:</br></br>
[place button here to link to web master cms error log form]
";
}

}
else
  {
  echo "<b>Error</b></br></br>
  None of the selected image files have been uploaded as a result of either or both of the following incidents occurring:</br></br>
  1) One or more of the submitted file types is not *.gif, *.jpeg or *.pjpeg.</br></br>
  2) All three file upload fields were left blank. (can this be prevented with validation?)</br></br>
  Click the back button on your browser to continue.
  ";
  }


?>

 

Here's the form itself:

 

<html>

<head>
<link rel="stylesheet" href="productpage.css" type="text/css" />
</head>

<body>


<strong>Please ensure that the image files have already been conventionally optimized for the web browsing.[link to learn how]
</br></br>While image files of any size can be uploaded it is strongly advised against.
</br></br>Excessivley large image files will significantly take longer to upload to the server, 
impede unnecessary server space and hinder the load time of particular sections of the site.</br></br>



<form action="inputdata4.php" method="post"
enctype="multipart/form-data">

<fieldset>
   
    <ol>

    <li>
    <label for="make">Make:</label>
    <input type="text" name="make" id="make" class="text">
    </li>
    <li>
    <label for="model">Model:</label>
    <input type="text" name="model" id="model" class="text">
    </li>
    <li>
    <label for="price">Price:</label>
    <input type="text" name="price" id="price" class="text">
    </li>			
    <li>
    <label for="engine">Engine:</label>
    <input type="text" name="engine" id="engine" class="text">
    </li>
    <li>
    <label for="body">Body Type:</label>
    <input type="text" name="body" id="body" class="text">
    </li>
    <li>
    <label for="transmission">Transmission:</label>
    <input type="text" name="transmission" id="transmission" class="text">
    </li>
    <li>
    <label for="year">Year:</label>
    <input type="text" name="year" id="year" class="text">
    </li>
    <li>
    <label for="colour">Colour:</label>
    <input type="text" name="colour" id="colour" class="text">
    </li>
    <li>
    <label for="mileagem">Mileage M:</label>
    <input type="text" name="mileagem" id="mileagem" class="text">
    </li>
    <li>
    <label for="mileagekm">Mileage KM:</label>
    <input type="text" name="mileagekm" id="mileagekm" class="text">
    </li>
    <li>
    <label for="owners">Owners:</label>
    <input type="text" name="owners" id="owners" class="text">
    </li>
    <li>
    <label for="doors">Doors:</label>
    <input type="text" name="doors" id="doors" class="text">
    </li>
    <li>
    <label for="location">Location:</label>
    <input type="text" name="location" id="location" class="text">
    </li>
    <li>
    <label for="info">Additional Info:</label>
    <textarea name="info" id="info"></textarea>			
    </li>
    <li>
    <label for "ufile[]">Image File 1:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    <li>
    <label for "ufile[]">Image File 2:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    <li>
    <label for "ufile[]">Image File 3:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    <li>
    <input type="submit" name="Submit" value="Submit" onclick = "this.style.visibility = 'hidden'; loading.style.visibility = 'visible';"/>
    </li>

    </ol>

</fieldset>

</form>

</body>
</html>

 

 

Its all functioning btw :)

Link to comment
Share on other sites

If you are uploading files, there is a subtle error condition that occurs when you exceed the maximum post size setting. The $_FILES and $_POST arrays are empty. The best way to detect this is if $_SERVER['REQUEST_METHOD'] == 'POST' (meaning a form or a script using the POST method submitted data to your code) and the $_FILES array is empty.

 

You must also test for upload errors before you attempt to access any of the uploaded file information. In the code posted so far, $_FILES["file"]["type"] is being tested before $_FILES["file"]["error"] is being tested. However, if there was an upload error, $_FILES["file"]["type"] will be empty and the code will report an "Invalid file. ...." when in fact it should report "Return Code: " . $_FILES["file"]["error"]..."

 

The following logic -

  if ($_FILES["file"]["error"] > 0)
  
  // CONDITION B THEN: an error return code is given

    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }

 

Must be executed before this logic -

 

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))

// CONDITION A THEN: 

  {

Link to comment
Share on other sites

Also I seem to be stuck on how or where to check if ...

 

$HTTP_POST_FILES['ufile']['name'][0]

$HTTP_POST_FILES['ufile']['name'][1]

$HTTP_POST_FILES['ufile']['name'][2]

 

... equal the same image (i.e. the user uploaded the same image more than once in the one submit)

Link to comment
Share on other sites

I did not see any mention of validating uploads at that link?

 

The following is (tested) code that will detect and handle all possible errors associated with uploads for both a single and multiple (using an array) file uploads (change the $_FILES['file'] name field to match the name you used in your form. Edit: This would be 'ufile" in the latest code you posted.) -

<?php
if($_SERVER['REQUEST_METHOD'] <> "POST")
{
// do any special processing when this page is reached direcly by the GET method...
} else {
if(empty($_FILES))
{
	echo "The file upload failed for one or more of the following reasons -";
	echo "<ol>";
	echo "<li>Uploads are not enabled on your server in php.ini</li>";
	echo "<li>The form tag does not contain - enctype=\"multipart/form-data\" or something else about the form makes it invalid</li>";
	echo "<li>There is no type=\"file\" field in the form</li>";
	echo "<li>The total size of the data from the form exceeds the post_max_size setting</li>";
	echo "</ol>";
} else {
	if(is_array($_FILES['file']['error'])){
		// for multiple files, ['error'], ['name'], ['tmp_name'], ['size'], and ['type'] elements will be set for each type=file form field
		foreach($_FILES['file']['error'] as $key => $value){
			switch ($_FILES['file']['error'][$key]) {
				case 0:
					// echo "The file uploaded to the server OK<br />";
					break;
				case 1:
					echo "The uploaded file exceeds the upload maximum size directive in php.ini<br />";
					break;
				case 2:
					echo "The uploaded file exceeds {$_POST['MAX_FILE_SIZE']}, the MAX_FILE_SIZE directive in the HTML form<br />";
					break;
				case 3:
					echo "The uploaded file was only partially uploaded<br />";
					break;
				case 4:
					echo "No file was selected<br />";
					break;
				case 6:	
					echo "Missing temporary upload folder<br />";
					break;
				case 7:
					echo "Failed to write file to disk<br />";
					break;
				case 8:
					echo "File upload stopped by extension<br />";
					break;			
				default:
					echo "An unused error value was returned<br />";
			} // end of switch/case
			if($_FILES['file']['error'][$key] == 0){
				// the file was uploaded 
				// use the uploaded file information here
				// put any type, size, file name/extension, or content validation here
				// The following will be set for each file - 
				// $_FILES['file']['name'][$key], $_FILES['file']['tmp_name'][$key], $_FILES['file']['size'][$key], and $_FILES['file']['type'][$key]
				echo "Process the uploaded file here<br />";
			}						
		} // end of foreach loop
	} else {
		switch ($_FILES['file']['error']) {
			case 0:
				// echo "The file uploaded to the server OK<br />";
				break;
			case 1:
				echo "The uploaded file exceeds the upload maximum size directive in php.ini<br />";
				break;
			case 2:
				echo "The uploaded file exceeds {$_POST['MAX_FILE_SIZE']}, the MAX_FILE_SIZE directive in the HTML form<br />";
				break;
			case 3:
				echo "The uploaded file was only partially uploaded<br />";
				break;
			case 4:
				echo "No file was selected<br />";
				break;
			case 6:	
				echo "Missing temporary upload folder<br />";
				break;
			case 7:
				echo "Failed to write file to disk<br />";
				break;
			case 8:
				echo "File upload stopped by extension<br />";
				break;			
			default:
				echo "An unused error value was returned<br />";
		} // end of switch/case
		if($_FILES['file']['error'] == 0){
			// the file was uploaded 
			// use the uploaded file information here
			// put any type, size, file name/extension, or content validation here
			// The following will be set for the file - 
			// $_FILES['file']['name'], $_FILES['file']['tmp_name'], $_FILES['file']['size'], and $_FILES['file']['type']
			echo "Process the uploaded file here<br />";
		}						
	} // end of single file else statement
}
}
?>

Link to comment
Share on other sites

Thanks, I'll start breaking this appart now.

 

The provided link only handles regular text input validation which I still can't get a handle on.

 

Most tutorials show me blocks of code but hardly none at all show me how it all stiches together.

 

(e.g. in your code I don't know what triggers the cases and how it should slot it with my code)

Link to comment
Share on other sites

:D Yay! I've done it! Well almost...

 

There's only two things left. Firstly how do I validate if (strlen($_POST['xxx']) > 0) for an array of three upload files (this is fixed so there won't be more or less than 3).

 

I've tried if (strlen($_POST['ufile[]']) > 0) but I get an error. PFMaBiSmAd's code looks great but I already validate the actual images when processing the form. All I need is a snippet of code to validate that the fields are not empty.

 

Secondly I'm not sure how to validate if a text area is empty since its html syntax is different from a reguler text input field

 

Here's the full code (please review it before answering - thanks)

 

<?php

if (isset($_POST['submit']))

//PROCESS THE FORM WHEN THE SUBMIT BUTTON IS PRESSED

{ 

//VALIDATE THE INDIVIDUAL TEXT FIELDS AND DEFINE THEM AS TRUE OR FALSE BASED ON THE USER'S INPUT

if (strlen($_POST['make']) > 0)
		{$make=TRUE;}
else 	{$make=FALSE;
		$message_make=" *You forgot to enter the make!";}


if (strlen($_POST['model']) > 0)
		{$model=TRUE;}
else 	{$model=FALSE;
		$message_model=" *You forgot to enter the model!";
		}


if (strlen($_POST['price']) > 0)
		{$price=TRUE;}
else 	{$price=FALSE;
		$message_price=" *You forgot to enter the price!";}


if (strlen($_POST['engine']) > 0)
		{$engine=TRUE;}
else 	{$engine=FALSE;
		$message_engine=" *You forgot to enter the engine!";}


if (strlen($_POST['body']) > 0)
		{$body=TRUE;}
else 	{$body=FALSE;
		$message_body=" *You forgot to enter the body!";}


if (strlen($_POST['transmission']) > 0)
		{$transmission=TRUE;}
else 	{$transmission=FALSE;
		$message_transmission=" *You forgot to enter the transmission!";}


if (strlen($_POST['year']) > 0)
		{$year=TRUE;}
else 	{$year=FALSE;
		$message_year=" *You forgot to enter the year!";}


if (strlen($_POST['colour']) > 0)
		{$colour=TRUE;}
else 	{$colour=FALSE;
		$message_colour=" *You forgot to enter the colour!";}


if (strlen($_POST['mileagem']) > 0)
		{$mileagem=TRUE;}
else 	{$mileagem=FALSE;
		$message_mileagem=" *You forgot to enter the mileage in miles!";}


if (strlen($_POST['mileagekm']) > 0)
		{$mileagekm=TRUE;}
else 	{$mileagekm=FALSE;
		$message_mileagekm=" *You forgot to enter the mileage in kilometres!";}


if (strlen($_POST['owners']) > 0)
		{$owners=TRUE;}
else 	{$owners=FALSE;
		$message_owners=" *You forgot to enter the owner!";}


if (strlen($_POST['doors']) > 0)
		{$doors=TRUE;}
else 	{$doors=FALSE;
		$message_doors=" *You forgot to enter the doors!";}


if (strlen($_POST['location']) > 0)
		{$location=TRUE;}
else 	{$location=FALSE;
		$message_location=" *You forgot to enter the location!";}



//IF ALL INPUT FIELDS ARE DEFINED AS TRUE
       		
if ($make && $model && $price && $engine && $body && $transmission && $year && $colour && $mileagem && $mileagekm && $owners && $doors && $location)

	{	

//THEN VALIDATE FILE UPLOADS

//FIRST CHECK FILE TYPE BUT NOT SIZE

if (

     (
     //BEGIN IMAGE FILE 1
     (
     ($HTTP_POST_FILES['ufile']["type"][0] == "image/gif")
     || ($HTTP_POST_FILES['ufile']["type"][0] == "image/jpeg")
     || ($HTTP_POST_FILES['ufile']["type"][0] == "image/pjpeg")
      )
     //&&($HTTP_POST_FILES['ufile']["size"][0] < 50000)
     //END IMAGE FILE 1
     )

     &&

     (
     //BEGIN IMAGE FILE 2
     (
     ($HTTP_POST_FILES['ufile']["type"][1] == "image/gif")
     || ($HTTP_POST_FILES['ufile']["type"][1] == "image/jpeg")
     || ($HTTP_POST_FILES['ufile']["type"][1] == "image/pjpeg")
     )
     //&&($HTTP_POST_FILES['ufile']["size"][1] < 50000)
     //END IMAGE FILE 2
     )

     &&

     (
     //BEGIN IMAGE FILE 3
     (
     ($HTTP_POST_FILES['ufile']["type"][2] == "image/gif")
     || ($HTTP_POST_FILES['ufile']["type"][2] == "image/jpeg")
     || ($HTTP_POST_FILES['ufile']["type"][2] == "image/pjpeg")
     )
     //&&($HTTP_POST_FILES['ufile']["size"][2] < 50000)
     //END IMAGE FILE 3
     )

)


{

//DEFINE PATHS AS VARIABLES

$path1= "upload/".$HTTP_POST_FILES['ufile']['name'][0];
$path2= "upload/".$HTTP_POST_FILES['ufile']['name'][1];
$path3= "upload/".$HTTP_POST_FILES['ufile']['name'][2];

//NEXT CHECK IF EITHER OF THE FILES ALREADY EXIST

if (file_exists($path1) || file_exists($path2) || file_exists($path3))
     
     {
     echo "<b>ERROR</b></br></br>
     1 One or more of the image files you attempted to upload already exist on the server. 
     Please ensure that you have not already uploaded the image file(s) and / or that each file name is unique.</br></br>
     Tip: Try naming the image files semantically after a combination of the make, model and year of the vehichle rather than a random series of letters and numbers.
     </br></br>
     Should you experience further technical difficulty please contact the web master:</br></br>
     [place button here to link to web master cms error log form]
     ";
     }


//NEXT POST THE IMAGES TO THE DESIGNATED FOLDER ON THE SERVER

else {

copy($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);
copy($HTTP_POST_FILES['ufile']['tmp_name'][1], $path2);
copy($HTTP_POST_FILES['ufile']['tmp_name'][2], $path3);

//PICK UP AND DEFINE INPUT AS INDIVIDUAL VARIABLES

                  $make = $_POST['make'];
                  $model = $_POST['model'];
                  $price = $_POST['price'];
                  $engine = $_POST['engine'];
                  $body = $_POST['body'];
                  $transmission = $_POST['transmission'];
                  $year = $_POST['year'];
                  $colour = $_POST['colour'];
                  $mileagem = $_POST['mileagem'];
                  $mileagekm = $_POST['mileagekm'];
                  $owners = $_POST['owners'];
                  $doors = $_POST['doors'];
                  $location = $_POST['location'];

//DEFINE ADDITIONAL VARIABLES

                  $now_datetime = date('Y-m-d h:i:s');
                  $ipaddress = getenv('REMOTE_ADDR');

//CONNECT TO RELEVANT DATABASE

                  include("dbinfo.php");
          mysql_connect(localhost,$username,$password);
          @mysql_select_db($database) or die( "Unable to establish a connection to the relevant database.");

//INSERT THE INPUT INTO DATABASE

$query = "INSERT INTO test VALUES ('','$make','$model','$price','$engine','$body','$transmission','$year','$colour','$mileagem','$mileagekm','$owners','$doors','$location','$info','$now_datetime','$ipaddress','$path1','$path2','$path1')";
mysql_query($query);

//NEXT DISPLAY A SUMMARY OF WHAT HAS BEEN UPLOADED

echo "This item has been successfully submitted to the server.</br></br>
The following image file have been appended to your uploaded:</br></br>
";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][0]."<BR/>"; 
//echo "File Size :".$HTTP_POST_FILES['ufile']['size'][0]." KB<BR/>"; 
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][0]."<BR/>"; 
//echo "<img src=\"$path1\" height=\"150\">";
echo "<P>";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][1]."<BR/>"; 
//echo "File Size :".$HTTP_POST_FILES['ufile']['size'][1]."<BR/>"; 
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][1]."<BR/>"; 
//echo "<img src=\"$path2\" height=\"150\">";
echo "<P>";

echo "File Name :".$HTTP_POST_FILES['ufile']['name'][2]."<BR/>"; 
//echo "File Size :".$HTTP_POST_FILES['ufile']['size'][2]."<BR/>"; 
echo "File Type :".$HTTP_POST_FILES['ufile']['type'][2]."<BR/>"; 
//echo "<img src=\"$path3\" height=\"150\">";

echo "</br>It's best practice to confirm that your item has been submitted as desired</br></br>
[place button here to link to view relevant section]</br></br>
If you notice an error as a result of human input please find and delete the item indefinitely and reattempt its submission. 
Itens should also be deleted as soon as they become redundant (e.g. vehichle sold)</br></br>
Should you experience further technical difficulty please contact the web master:</br></br>
[place button here to link to web master cms error log form]
";
}

}
else
  {
  echo "<b>Error</b></br></br>
  1) One or more of the submitted file types is not *.gif, *.jpeg or *.pjpeg.</br></br>
  Click the back button on your browser to continue.
  ";
  }

//VERY IMPORTANT! EXIT(); WILL NO LONGER DISPLAY THE FORM
               exit();

	}

} 

//END FORM PROCESS

?>

<HTML>
<HEAD>
</HEAD>
<BODY>


<!--BEGIN FORM AND SET IT TO PROCESS SELF AND HANDLE MULTIPART/FORM-DATA-->

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

<fieldset>

<?php

// IF ANY INDIVIDUAL INPUT FIELD IS DEFINED AS FALSE THEN DISPLAY ERROR MESSAGE 

if ($message_make || $message_model || $message_price || $message_engine || $message_body || $message_transmission || $message_year || $message_colour || $message_mileagem || $message_mileagekm || $message_owners || $message_doors || $message_location) 
echo '*Your request could not be sent because some of the information is missing.</br></br>'; 

?>
   
<ol>

<!--BEGIN REGULAR TEXT FIELDS-->

    <li>
    <label for="make">Make:</label>
    <input type="text" name="make" id="make" class="text" value="<?php if (isset($_POST['make'])) echo $_POST['make']; ?>"/>
    <?php if ($message_make) echo ''.$message_make.''; ?></br>
    </li>

    <li>
    <label for="model">Model:</label>
    <input type="text" name="model" id="model" class="text" value="<?php if (isset($_POST['model'])) echo $_POST['model']; ?>"/>
    <?php if ($message_model) echo ''.$message_model.''; ?></br>
    </li>

    <li>
    <label for="price">Price:</label>
    <input type="text" name="price" id="price" class="text" value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>"/>
    <?php if ($message_price) echo ''.$message_price.''; ?></br>
    </li>	

    <li>
    <label for="engine">Engine:</label>
    <input type="text" name="engine" id="engine" class="text" value="<?php if (isset($_POST['engine'])) echo $_POST['engine']; ?>"/>
    <?php if ($message_engine) echo ''.$message_engine.''; ?></br>
    </li>

    <li>
    <label for="body">Body Type:</label>
    <input type="text" name="body" id="body" class="text" value="<?php if (isset($_POST['body'])) echo $_POST['body']; ?>"/>
    <?php if ($message_body) echo ''.$message_body.''; ?></br>
    </li>

    <li>
    <label for="transmission">Transmission:</label>
    <input type="text" name="transmission" id="transmission" class="text" value="<?php if (isset($_POST['transmission'])) echo $_POST['transmission']; ?>"/>
    <?php if ($message_transmission) echo ''.$message_transmission.''; ?></br>
    </li>

    <li>
    <label for="year">Year:</label>
    <input type="text" name="year" id="year" class="text" value="<?php if (isset($_POST['year'])) echo $_POST['year']; ?>"/>
    <?php if ($message_year) echo ''.$message_year.''; ?></br>
    </li>

    <li>
    <label for="colour">Colour:</label>
    <input type="text" name="colour" id="colour" class="text" value="<?php if (isset($_POST['colour'])) echo $_POST['colour']; ?>"/>
    <?php if ($message_colour) echo ''.$message_colour.''; ?></br>
    </li>

    <li>
    <label for="mileagem">Mileage M:</label>
    <input type="text" name="mileagem" id="mileagem" class="text" value="<?php if (isset($_POST['mileagem'])) echo $_POST['mileagem']; ?>"/>
    <?php if ($message_mileagem) echo ''.$message_mileagem.''; ?></br>
    </li>

    <li>
    <label for="mileagekm">Mileage KM:</label>
    <input type="text" name="mileagekm" id="mileagekm" class="text" value="<?php if (isset($_POST['mileagekm'])) echo $_POST['mileagekm']; ?>"/>
    <?php if ($message_mileagekm) echo ''.$message_mileagekm.''; ?></br>
    </li>

    <li>
    <label for="owners">Owners:</label>
    <input type="text" name="owners" id="owners" class="text" value="<?php if (isset($_POST['owners'])) echo $_POST['owners']; ?>"/>
    <?php if ($message_owners) echo ''.$message_owners.''; ?></br>
    </li>

    <li>
    <label for="doors">Doors:</label>
    <input type="text" name="doors" id="doors" class="text" value="<?php if (isset($_POST['doors'])) echo $_POST['doors']; ?>"/>
    <?php if ($message_doors) echo ''.$message_doors.''; ?></br>
    </li>

    <li>
    <label for="location">Location:</label>
    <input type="text" name="location" id="location" class="text" value="<?php if (isset($_POST['location'])) echo $_POST['location']; ?>"/>
    <?php if ($message_location) echo ''.$message_location.''; ?></br>
    </li>

<!--BEGIN TEXT AREA-->

<!--BEGIN FILE UPLOADS-->

    <li>
    <label for "ufile[]">Image File 1:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    <li>
    <label for "ufile[]">Image File 2:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    <li>
    <label for "ufile[]">Image File 3:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    
    <li>
    <input name="submit" type="submit">
    </li>

</ol>

</fieldset>

</form>	

</BODY>
</HTML>

 

Link to comment
Share on other sites

Oops! Here's the text area:

 

<textarea name="info" rows="5" cols="50"/>
<?php if (isset($_POST['info'])) echo stripslashes($_POST['info']); ?>
</textarea>

 

Solving this portion.

 

<?php
if (isset($_POST['info'])) {
    $info = trim($_POST['info']);
    if ($info == "" || empty($info)) {
        $message_info = "Please enter data for info!";
   }
}
?>

 

Trim should trim out any whitespaces at the end/breaks and empty will check if PHP considers the variable to be empty. Untested but I am pretty sure that would work.

Link to comment
Share on other sites

That worked great. Thanks Premiso.

 

Any takers on the validating the file upload:

 

    <li>
    <label for "ufile[]">Image File 1:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    <li>
    <label for "ufile[]">Image File 2:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>
    <li>
    <label for "ufile[]">Image File 3:</label>
    <input type="file" name="ufile[]"  id="ufile[]"/> 
    </li>

 

I just need to check if the fields are empty.

 

(If you're feeling extra generous I need to check if any of them equal each other  :P)

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.