How to validate 2 forms at once

Posted on 2016-11-04
Last Modified: 2016-11-05
I need a bit of help with the logic of this, please.

I have 2 forms. The one form has text fields and drop downs that have be filled in e.g.: product name, price, category etc.

Then next to it I have another form with the ability to upload a single image which is meant to be a featured image.

When I click submit I want to be able to check that an image has been selected and  uploaded. But the problem is that the image has it's own form with it's own upload button that needs to be pressed.

So, if I click on submit to add a product, it is only checking that the submit button was pressed and not that the upload button had already been pressed. Not sure if I am making any sense as it's hard to explain. I will post some code which might help.

here is an example of some of the validation for the main form with all the details of the product with a button name of "add_product"

if(isset($_POST['add_product'])) {
		if(empty($_POST['prod_name'])) {
			$message .= "Product name required <br />";
		if(empty($_POST['category'])) {
			$message .= "Category required <br />";

Open in new window

The upload form:

<form id="form" action="ajaxupload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" class="form-control" />
<input type="submit" id="button" name="upload" class="btn btn-fill btn-danger" value="Upload" />

Open in new window

I thought about putting the image upload into the same form so they were both in 1 form but it isn't possible because the form with the image upload posts to ajaxupload.php and the other form is going to submit to the database.
Question by:Black Sulfur

Author Comment

by:Black Sulfur
ID: 41874248
This is the php on the ajaxupload.php

$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory

 $img = $_FILES['image']['name'];
 $tmp = $_FILES['image']['tmp_name'];
 // get uploaded file's extension
 $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
 // can upload same image using rand function
 $final_image = rand(1000,1000000).$img;
 // check's valid format
 if(in_array($ext, $valid_extensions)) 
  $path = $path.strtolower($final_image); 
  echo "<img src='$path' width='164px' />";

  echo 'invalid file';

Open in new window

I thought that maybe I could set a variable once they upload has completed and then check if it exists when I try submit the other form but not sure. So, after I echo the image, I set something like:

  echo "<img src='$path' width='164px' />";
 $file_upload = true;

Open in new window

LVL 109

Expert Comment

by:Ray Paseur
ID: 41874669
Why not just use one form?  It's a POST-method request, so you can send other fields along with the file upload.

To expand on the idea a little more, each form submission is made via an HTTP request.  If you can make one request instead of two, your application design will be greatly simplified!

Looking forward to the redesign that you're going to have to do after this initial implementation is set up, you might want to consider these ideas...

1. All images associated with a product must be replaceable.
2. All data fields associated with a product must be replaceable.
3. The order of presentation for the images must be user-settable.
4. Any image must be able to be deleted or overwritten.

When you take those ideas into account you will come to a set of simpler table maintenance scripts, and the programming (as well as the application) will be simplified.

Author Comment

by:Black Sulfur
ID: 41874682
I want to be able to see the preview of the image uploaded which means the image needs to upload first. Doesn't that mean it has to be in a seperate form to upload separately to submitting the form with all the text fields? perhaps I am just making this too complicated because I want it to work like the wordpress version.

I have uploaded an image so you can see what I mean. I want to upload the image and show it on the right. Then if the user hasn't uploaded the image, when they click the button on the left form they should get an error to say that they need to upload an image. I just like the idea of them being able to see a thumbnail of the image they uploaded instead of just seeing the filename.
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 41874794
You might find that you can preview image uploads with some HTML5 controls.  See if this looks good...
<?php // demo/upload_image_preview.php

if (!empty($_FILES)) die( var_dump($_FILES) );

$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<style type="text/css">
.preview img {
    border: 1px solid gray;

<script src=""></script>
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $(".preview img").attr("src",;

    $(".upld").change(function () {

<title>File Upload With Image Preview</title>

<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<div class="preview"><img src="" /></div>
<form enctype="multipart/form-data" method="post">
<input type="file" class="upld" name="myfile" />
<input type="submit" value="Upload" />


echo $htm;

Open in new window

LVL 82

Accepted Solution

hielo earned 275 total points
ID: 41875159
>> When I click submit I want to be able to check that an image has been selected and  uploaded.
OK, from what you already have, since you two different files -- ajaxupload.php and whatever.php (for the product name, etc) -- since these files execute at different times, you cannot use $file_upload = true; because it will exist only in ajaxupload.php while it is processing the upload.  What you need to do is to use $_SESSION variables.  Put the following at the start of your ajaxupload.php:
//rest of your code follows
// then intead of
// $file_upload = true;
// use

Open in new window

whatever.php also need to start with:

//rest of your code here
//and then to see if the file was uploaded use:
if( array_key_exists('file_uploaded',$_SESSION) && true===$_SESSION['file_uploaded'])
  // file was uploaded

Open in new window


Author Comment

by:Black Sulfur
ID: 41875191
Okay, both of these are great so far. Thanks guys!  

Great idea with the session variable, that worked perfectly. Only one issue with it..

If I don't upload an image and I try submit, I now get the error message I set that says I need to upload an image. If I upload the image and submit, I don't get the error which is exactly what I want to happen. BUT, if there is something else wrong with the form and it is submitted (like a field left empty for example), it shows the errors and the image that was uploaded disappears now. I assume that's because when I submit the form it is posting and refreshing the page.

I tried to put the uploaded image into a session variable as well so that it would still display even after page refresh but that didn't work.

 $_SESSION['imguploaded'] = true;
	$_SESSION['showimage'] = "<img src='$path' width='164px' />";
	   echo $_SESSION['showimage'];

Open in new window

LVL 19

Assisted Solution

NerdsOfTech earned 25 total points
ID: 41875208
I recommend that there be 1 form (multi-part type) and that the upload button initiate a "local" preview of the image (load file from users hard drive via file: protocol when the upload button is clicked {onclick}) . The submit button will act as the true upload button. Attach a Javascript OnSubmit procedure to the submit button to check to see if the file is present or  stop the submission of the form (Javascript: return false;) until the image is present.

Author Comment

by:Black Sulfur
ID: 41875398
Trying to use 2 forms is way too complicated for me at this stage I would say. I think I will take the advice of using 1 form. However, I must say that the session variable method was working for me but trying to show the image straight away was an issue and a bunch of other stuff. I have got some good advice here to get me going though. Thanks to all!

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Google Maps API and PHP 25 49
How to check if a session is disconnected in php 9 31
Restricting the scope of variables to private in OOP 4 22
Inserting data into database 10 34
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Introduction This article is intended for those who are new to PHP error handling (  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question