0

So I have two files, one is index.php and register.php. Index is the form and register is the PHP handling the form. So here's index.php

        <!DOCTYPE html>
    <html lang="en">
      <body>

        <div class="container">

          <form class="form-signin" role="form" action="register.php" method="post">
            <h2 class="form-signin-heading">Please sign up</h2>
            <input type="text" class="form-control" placeholder="Name"  name="name" autofocus style="border-color:#<?php   ?>;">
             <input type="text" class="form-control" placeholder="Username"  name="username" autofocus>
            <input type="text" class="form-control" placeholder="Email"  name="email" autofocus>
            <input type="password" class="form-control" placeholder="Password" name="password">
            <input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
            <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
          </form>

        </div> 



      </body>
    </html>

And my register.php

        <?php
    try {
    $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    exit($e->getMessage());
}

//Post
$name = $_POST['name']; 
$username = $_POST['username']; 
$email = $_POST['email'];   
$password = $_POST['password']; 
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];




//Verifcation 
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1))
    {
    echo "Complete all fields";
    }

// Password match
if ($password != $password1)
    {
    echo $passmatch = "Passwords don't match";
    }

// Email validation

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
    echo $emailvalid = "Enter a  valid email";
    }

// Password length
if (strlen($password) <= 6){
    echo $passlength = "Choose a password longer then 6 character";
}

if(empty($passmatch) && empty($emailvalid) && empty($passlength)) {

//Securly insert into database
$sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';    
$query = $handler->prepare($sql);

    $query->execute(array(

    ':name' => $name,
    ':username' => $username,
    ':email' => $email,
    ':password' => $password,
    ':ip' => $ip

    ));
    }
        ?>

But here's what I want to do, I want to display the PHP errors alongside the form instead of having them displayed on register.php But I also want to use two separate files. Instead of combining the two files together. Any ideas?

user3574362
  • 95
  • 1
  • 2
  • 7

4 Answers4

0

I seriously don't understand your use of server side to do all these validations. It is wise and economical to do this in the client side itself. There are a hell lot of plugins for client side form validation, if that's the case for you.

A few scripts would be:

Find the last link to do the work yourself.

In your case, please try to separate the view and logic. It is also wise to follow Model-View-Controller architecture that is followed in many of the PHP Web Applications and JavaScript Apps now-a-days.


Or if you somehow need the logic to be done in server side, separate the form by putting the HTML inside form.php. And in your validation, do a small change, by including a flag, which is set to false, when the form is not validated.

Now, if the validation is not successful, i.e., the flag $valid = false, then you include the form.inc, else include success.inc.

if ($valid)
    include 'success.inc';
else
    include 'form.inc';

And since it is going to be in the same file, in the form.inc, add this line:

if (!$valid)
    echo '<p class="error">You have errors in your form! Please correct them!</p>';
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 7
    Server side validation is *imperative* for crucial checks like duplicate E-Mails, user names, anything that you need to be able to count on to be correct. See e.g. http://stackoverflow.com/questions/162159/javascript-client-side-vs-server-side-validation Client side validation is always nice, but only for the user's convenience. – Pekka Apr 26 '14 at 02:02
  • 1
    I'm going to have to agree with @Pekka웃 on this. Client-side validation should be a measure used _in addition to_, not in place of, server-side validation. – Patrick Q Apr 26 '14 at 02:05
  • I am also agreeing with @Pekka웃 but won't server side validation be a costly issue? Just my instinct. Yes, DB operations I do validate from server side before I commit. :) – Praveen Kumar Purushothaman Apr 26 '14 at 02:10
  • server side validation may be costly, but a necessity if you don't want people using cURL to inject bad data into your database. Client-side is good too, to prevent a majority of people even getting to the server at all. – Michael Butler Apr 26 '14 at 02:12
  • Would I create `form.php`? – user3574362 Apr 26 '14 at 02:13
  • Yes. You can. Anything is fine. `form.inc` clearly shows that it is an include file and not a file that can be opened by the user by typing in the browser. `#GoodPractice` – Praveen Kumar Purushothaman Apr 26 '14 at 02:14
0

At the bottom of register.php simply call:

include 'index.php';

And your form will be displayed.

Add a line to display errors in your index.php:

<?php if (!empty($error)) { ?>
<?php echo "error occured: ".$error; ?>
<?php } ?>

This is a style of MVC programming (Model-View-Controller). The idea is not to echo things all over the place within register.php, instead you build up an application state in a model and then the view (index.php) reads from the model.

Michael Butler
  • 6,079
  • 3
  • 38
  • 46
0

register.php

 <?php
//Connections
try {
    $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    exit($e->getMessage());
}

//Post shit
$name = $_POST['name']; 
$username = $_POST['username']; 
$email = $_POST['email'];   
$password = $_POST['password']; 
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];

$error = null;//set it to null
//Verifcation 
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1)){
    $error .= "Complete all fields\n";
}

// Password match
if ($password != $password1){
    $error .= "Passwords don't match\n";
}

// Email validation

if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
    $error .= "Enter a  valid email\n";
}

// Password length
if (strlen($password) <= 6){
    $error .= "Choose a password longer then 6 character\n";
}

if(!isset($error)){
//no error
$sthandler = $handler->prepare("SELECT username FROM users WHERE username = :name");
$sthandler->bindParam(':name', $username);
$sthandler->execute();

if($sthandler->rowCount() > 0){
    error .= "exists! cannot insert\n";
} else {
    //Securly insert into database
    $sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES (:name,:username,:email,:password,:ip)';    
    $query = $handler->prepare($sql);

    $query->execute(array(

    ':name' => $name,
    ':username' => $username,
    ':email' => $email,
    ':password' => $password,
    ':ip' => $ip

    ));
    }
}else{
    error .= "error occured: ".$error;
}

if(!isset($error)){
header( 'Location: index.php' ) ;
} 
else {
header( 'Location: register.php?err='.$error ) ;
}

To display the error on your form place this code:

if(isset($_GET['err'])){
  $error = $_GET['err'];
  echo "error: $error";
}
meda
  • 45,103
  • 14
  • 92
  • 122
0

Try this out:

<!DOCTYPE html>
    <html lang="en">
      <body>

        <div class="container">



      <?php
if(isset($_POST['submit'])){
    try {
    $handler = new PDO('mysql:host=localhost;dbname=s','root', '*');
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e){
    exit($e->getMessage());
}

//Post
$name = $_POST['name']; 
$username = $_POST['username']; 
$email = $_POST['email'];   
$password = $_POST['password']; 
$password1 = $_POST['passwordconf'];
$ip = $_SERVER['REMOTE_ADDR'];




//Verifcation 
if (empty($name) || empty($username) || empty($email) || empty($password) || empty($password1))
    {
    echo "Complete all fields";
    } if ($password != $password1)
    {
    echo $passmatch = "Passwords don't match";
    } else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
    echo $emailvalid = "Enter a  valid email";
    } else if (strlen($password) <= 6){
    echo $passlength = "Choose a password longer then 6 character";
    } if(empty($passmatch) && empty($emailvalid) && empty($passlength)) { // You don't need this line, you already checked above if these POST variables were empty. 
    //Securly insert into database
    $sql = 'INSERT INTO userinfo (name ,username, email, password, ip) VALUES      (:name,:username,:email,:password,:ip)';    
    $query = $handler->prepare($sql);

    $query->execute(array(

    ':name' => $name,
    ':username' => $username,
    ':email' => $email,
    ':password' => $password,
    ':ip' => $ip

    ));
    }
}
        ?>

          <form class="form-signin" role="form" action="" method="post">
            <h2 class="form-signin-heading">Please sign up</h2>
            <input type="text" class="form-control" placeholder="Name"  name="name" autofocus style="border-color:#<?php   ?>;">
             <input type="text" class="form-control" placeholder="Username"  name="username" autofocus>
            <input type="text" class="form-control" placeholder="Email"  name="email" autofocus>
            <input type="password" class="form-control" placeholder="Password" name="password">
            <input type="password" class="form-control" placeholder="Password, Again" name="passwordconf" >
            <button class="btn btn-lg btn-primary btn-block" name='submit' type="submit">Sign up</button>
          </form>

        </div> 



      </body>
</html>

Few notes:

  • Leaving the action value blank will cause the form to post back to itself.
  • I will fix the spacing when I get home, I don't have my editor with me.
  • The errors should be displayed underneath the container. I made it so that only one error is display at a time, do let me know if you want to display all the errors at once.
  • I wouldn't recommend doing the registration form this way, it's way too messy. However, if this is your learning process, then all the power to you.