1

Form validation in php when form action is another page (php code). How do I validate the form and display error message in view page?

view page

<html>
<body>
<form action="redirect.php" method="POST" enctype="multipart/form-data">  
    <label for="name"><b>Name: </b></label>
    <input type="text"  name="name" id="name" >
<br>
    <label for="email"><b>Email: </b></label>
    <input type="text"  name="email" id="email" >
<br>
    <label for="email"><b>Project Type: </b></label>
    <input type="text"  name="projecttype" id="projecttype">
<br>
    <label for="email"><b>Project Description: </b></label>
    <input type="text"  name="pdescription" id="pdescription" >
<br>
    <label for="file"><b>File Upload: </b></label>
    <input type="file"  name="file"  id="file">
<br>
    <div class="clearfix">
      <input type="submit" name="submit1" id="submit1" value="submit1">
    </div>  
</form>
</body>
</html>

redirect.php

<?php
if(isset($_POST['submit1'])) 
{
    $name=$_POST['name'];
    $email=$_POST['email'];
    $projecttype=$_POST['projecttype'];
    $projectdetails=$_POST['pdescription'];
    $attachment=$_FILES['file']['name'];
    $tmp_name=$_FILES['file']['tmp_name'];
    move_uploaded_file($tmp_name,"upload/".$attachment);
    $query=mysql_query("insert into projectdetails(Customer_name,Customer_email,Customer_attachment,Customer_project_type,Customer_project_details) values('$name','$email','$attachment','$projecttype','$projectdetails')");
    if($query)
    {   
        header('Location: test2.php');      
    }
    ?>
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
Swathi
  • 61
  • 1
  • 10
  • use `java script validation` for that or use `html 5 required validation` – Bhargav Chudasama Feb 20 '18 at 05:45
  • Why not use [jQuery Validation](https://jqueryvalidation.org/) or use simply jquery to validate your form ? – Sulthan Allaudeen Feb 20 '18 at 05:45
  • You validate the data, store errors and the initial data in a session, redirect back to the form and display errors and repopulate the form from the session. Alternative, use Ajax to save the form. – M. Eriksson Feb 20 '18 at 05:46
  • @Bhargav...i need form validation in php – Swathi Feb 20 '18 at 05:46
  • 1
    @Bhargav - Even if you validate the data using JS, you still need to validate it in the back end as well. _Never_ trust anything that comes from the front end. – M. Eriksson Feb 20 '18 at 05:46
  • so try to use `session` for store error message – Bhargav Chudasama Feb 20 '18 at 05:46
  • @SulthanAllaudeen.....i need form validation in php – Swathi Feb 20 '18 at 05:47
  • @MagnusEriksson....give me one small example – Swathi Feb 20 '18 at 05:49
  • do you have html and php code in same file redirect.php? – Javed Sayyed Feb 20 '18 at 05:53
  • FYI you also need to validate the file-upload module. As it is now, anyone can upload even a trojan file – Rotimi Feb 20 '18 at 05:56
  • 1
    1. **Don't** use the **deprecated and insecure** `mysql_*`-functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead. 2. **You are wide open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php)** and should really use [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of concatenating your queries, which can be used if you use the above mentioned MySQLi or PDO. – M. Eriksson Feb 20 '18 at 05:57
  • @Swathi You dont need to send another page for validation – Sulthan Allaudeen Feb 20 '18 at 06:01

4 Answers4

1

create simple demo for name field required in php using session

you can try this way

form.php

<?php
    session_start();
    if(isset($_SESSION['msg'])){
        $name=$_SESSION['msg']['name'];
    }
?>
<html>
<body>
<form action="redirect.php" method="POST" enctype="multipart/form-data">  
    <label for="name"><b>Name: </b></label>
    <input type="text"  name="name" id="name" > <span style="color:red"><?php echo $name ?></span>
<br>
    <label for="email"><b>Email: </b></label>
    <input type="text"  name="email" id="email" >
<br>
    <label for="email"><b>Project Type: </b></label>
    <input type="text"  name="projecttype" id="projecttype">
<br>
    <label for="email"><b>Project Description: </b></label>
    <input type="text"  name="pdescription" id="pdescription" >
<br>
    <label for="file"><b>File Upload: </b></label>
    <input type="file"  name="file"  id="file">
<br>
    <div class="clearfix">
      <input type="submit" name="submit1" id="submit1" value="submit1">
    </div>  
</form>
</body>
</html>

redirect.php

<?php
session_start();
if(isset($_POST['submit1'])) 
{

    $name=$_POST['name'];

    if(isset($name) && empty($name)){
        $_SESSION['msg']['name']="Name must be required!";
        header('location: form.php');  
        exit;
    }
    $email=$_POST['email'];
    $projecttype=$_POST['projecttype'];
    $projectdetails=$_POST['pdescription'];
    $attachment=$_FILES['file']['name'];
    $tmp_name=$_FILES['file']['tmp_name'];
    move_uploaded_file($tmp_name,"upload/".$attachment);
    $query=mysql_query("insert into projectdetails(Customer_name,Customer_email,Customer_attachment,Customer_project_type,Customer_project_details) values('$name','$email','$attachment','$projecttype','$projectdetails')");
    if($query)
    {   
        header('Location: test2.php');      
    }
}
?>
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
0

There are many ways to do that the simple way I would suggest to use HTML5

 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>

$(function () {
        $('form').bind('click', function (event) {
         event.preventDefault();
         $.ajax({
            type: 'POST',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });
      });
    <html>
    <body>
    <form action="redirect.php" method="POST" enctype="multipart/form-data">  
        <label for="name"><b>Name: </b></label>
        <input type="text"  name="name" id="name" required>
    <br>
        <label for="email"><b>Email: </b></label>
        <input type="email"  name="email" id="email" required>
    <br>
        <label for="email"><b>Project Type: </b></label>
        <input type="text"  name="projecttype" id="projecttype" required>
    <br>
        <label for="email"><b>Project Description: </b></label>
        <input type="text"  name="pdescription" id="pdescription" required>
    <br>
        <label for="file"><b>File Upload: </b></label>
        <input type="file"  name="file"  id="file" required>
    <br>
        <div class="clearfix">
          <input type="submit" name="submit1" id="submit1" value="submit1">
        </div>  
    </form>
    </body>
    </html>

In PHP PAge :

if(empty($_POST['name'])){
 echo "Name is required";
}
Nikita Agrawal
  • 235
  • 1
  • 11
  • This is far from enough to validate user inputs. Anyone can easily just bypass the form altogether and post directly to the action or even modify the HTML using "Inspect code" and remove any "required" or typed fields. Never ever trust data that comes from the front end. – M. Eriksson Feb 20 '18 at 05:53
  • you'll be better off with server-side validation – Rotimi Feb 20 '18 at 05:54
0

Set errors in a session before redirecting, echo them on the view page then unset the errors at the top of redirect.php, by unsetting them at the top you will make sure you always have the most recent error messages.

0

Severe issue in your code

  1. Do not use mysql_* functions in PHP

Fine tuning that can be done in your code

  1. You don't need to send your input to another page just for validation

Some examples for you

Client Side form Validation

PHP MySQLi Basic Examples

If you need to proceed in your current implementation

Declare a variable called as $formavalid and make it true and false accordingly

<html>
<body>
<?php 
$formvalid = true;
?>
<form action="redirect.php" method="POST" enctype="multipart/form-data">  
    <label for="name"><b>Name: </b></label>
    <input type="text"  name="name" id="name" >
<br>
    <label for="email"><b>Email: </b></label>
    <input type="text"  name="email" id="email" >
<?php
//Do like this for all fields
if(isset($_POST['submit1'])) 
{
if(!isset($_POST['email'])) 
{
echo 'Email field is missing';
}else{
$formvalid = false;// Make the $formvalid as false if your input is dirty
}
}
<br>
    <label for="email"><b>Project Type: </b></label>
    <input type="text"  name="projecttype" id="projecttype">
<br>
    <label for="email"><b>Project Description: </b></label>
    <input type="text"  name="pdescription" id="pdescription" >
<br>
    <label for="file"><b>File Upload: </b></label>
    <input type="file"  name="file"  id="file">
<br>
    <div class="clearfix">
      <input type="submit" name="submit1" id="submit1" value="submit1">
    </div>  
</form>
<?php
if($formvalid==true){
//Form is valid so do the action for it
}else{
//form is not valid, so let the user input to make it valid
}
?>
</body>
</html>

Hope, this helps you

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
  • If you look at the question, I think the OP wants to redirect back to the form page (the form is on another page) and show the errors there. – M. Eriksson Feb 20 '18 at 05:55
  • @MagnusEriksson Ahm, then it should be check and send back to display – Sulthan Allaudeen Feb 20 '18 at 05:57
  • Jupp. flash sessions for the errors and post data (to repopulate the form). – M. Eriksson Feb 20 '18 at 05:58
  • Obviously, I think the better approach will be form validation from client side using jquery and then do validation on server side too (for safe zone) – Sulthan Allaudeen Feb 20 '18 at 06:00
  • 1
    I totally agree. I even think it's a better solution to just use Ajax to validate/save the form. Maybe have two steps. First validate the oridnary inputs, then post the form (no need to send the file when validating the text). Then save it using Ajax (and do the same validation, for security but this time, send the file as well). Specially since it include file uploads. Nicer to have a spinner/progress bar than a blocking HTTP request. – M. Eriksson Feb 20 '18 at 06:03
  • 1
    Yeah, that's the universal way. Modifying the answer to tell the better way to handle – Sulthan Allaudeen Feb 20 '18 at 06:08