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.
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

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

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

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

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

770 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