-3

I'm currently working on a registration system and ran into some problem.
I'll start with pasting a simplified version of the code before:

session_start();

if (isset($_SESSION['logged_in'])) {

header('Location: #notLoggedIn');
exit;
} else {
if ($_SERVER["REQUEST_METHOD"] == "POST") {

        if //if field is empty {
            //display error
        } else if //check if any unallowed characters {
            //display another error
        } else {
            //give the checked input a string/variable, ex: $name= ($_POST["name"]);
        }

        // Like 4-5 other checks running in the same way as above

    }

    $query = $pdo->prepare('INSERT INTO table (a, b, c, d, e) VALUES (?,?,?,?,?)');

    $query->bindValue(1, $1);
    $query->bindValue(2, $2);
    $query->bindValue(3, $3);
    $query->bindValue(4, $4);
    $query->bindValue(5, $5);

    $query->execute();

    header('Location: index.php');
    exit;
    }

The problem is the fact that it runs everything at once and just redirects me to index.php.
How do I make sure it first of all checks if the form has been submitted before running.
After that I want it to check for any errors in ALL fields. If there are errors, stop.
But if there are no errors, just continue on and upload to my database.

I do think that I'm on a goodway, but currently pretty stuck, any help or push in the correct direction would be awesome!
Thank you!

Casper
  • 3
  • 4
  • It depends on what is inside your error-checking conditions. At the very least you should make sure that the dabase insert and redirect is not performed when there are errors. – jeroen Oct 12 '14 at 01:04
  • @jeroen I updated the above "checks" a little. But it does also depend on what input field it is, if it's the username for example, it first makes sure it's not empty and then check if there are any unallowed characters. But if it's just a normal name that is not "required" to register, it will just check for unallowed characters. – Casper Oct 12 '14 at 01:11
  • 1
    what is the ultimate goal? making a new user or logging in or...? – gloomy.penguin Oct 12 '14 at 01:30
  • @gloomy.penguin I really don't have a ultimate goal, i'm just expanding forward if I feel that I need to. It's just a personal project for to learn about PHP. I already have a working login function, and currently want a working register function :) – Casper Oct 12 '14 at 01:33

3 Answers3

0

Your question isn't exactly clear, nor is your code which is also incomplete (where is the form?).
You seem to be at an early stage of learning the form handling, and likely would benefit from further reading and testing before you ask specific questions.

Here are some starters:
http://en.wikipedia.org/wiki/Post/Redirect/Get
What's the best method for sanitizing user input with PHP?
The definitive guide to form-based website authentication

I'll give some info anyway, as have some free time.

For example, your first if checks if session IS set, if TRUE redirect to notLoggedIn. Are you sure this is intentional? Either they're logged in, echo message to suit, or not and so show the reg page (most sites show a login and reg on the same page, for convenience for all scenarios).

As this is a registration form, surely you meant if IS logged in then redirect to YouAreAlreadyLoggedIn?
In fact, I'd just exit a message "You are already logged in" then stop the script.

The problem is the fact that it runs everything at once and just redirects me to index.php.

That's because it has no other option, as at the end of your script after XYZ it redirects to index.php.
If you do not want it to do this then change it. Either don't redirect, handle the entire process more constructively, or exit at some point you need it to (like form errors).

How do I make sure it first of all checks if the form has been submitted before running.

I don't see a form, so don't know exactly what you are doing to advise.

Ideally you'd use the PRG (Post Redirect Get).
http://en.wikipedia.org/wiki/Post/Redirect/Get

Your Script

I've edited your script to make this an answer to the question, and tidied it up a little.

e.g. in your script, specifically at the top, you don't need the else as there's an exit() in the if. When the if returns true, the script will stop, otherwise (with or without an else) it will continue.

The code:

session_start();


if (isset($_SESSION['logged_in']))
  {
    exit('You are already logged in');
  }



if ($_SERVER["REQUEST_METHOD"] == "POST")
  {

    if ( strlen($POST['field_name']) < 4 )
      {
        exit('Minimum 4 chars required');
      }
    elseif ( strlen($POST['field_name']) > 20 )
      {
        exit('Max of 20 chars allowed');
      }
    elseif ( preg_match("/^[A-z0-9]+$/", $POST['field_name']) != 1 )
      {
        exit('Invalid chars - allowed A-z and 0-9 only');
      }
     else
      {
        // Not sure what you want here
        // If all ok (no errors above)
        // then sanatise the data and insert into DB
      }

  }

As for entering into the DB, you need much more checking and handling of the entire process before you just allow the DB stuff to run.

Not sure why you redirect to index.php. You'd then need to handle form submission results in index.php to tell user you are registered. On the form page, tell them the errors they have in the fields, or echo out the success message and what happens next (i.e. go to your account page, or (hopefully) confirm the email you sent before logging in).

As for the validation checks in the POSTed form data, it's entirely up to you what you need. But I've given you some very basic to go on. Make sure your max set in the form matches the database column allowance, or if (eg) DB varchar is set to 15 and you allow users to enter 20, the data they enter will be truncated, and they'll register, but never be able to login (or some other data will be broken, their name/username etc).

Community
  • 1
  • 1
James
  • 4,644
  • 5
  • 37
  • 48
  • I do have a
    with several fields already and all that setup, but I though leaving all the "simple" code out would make more try to help me, I guess it turned the opposite, hehe. Thank you for the very detailed post, all the three posts above have definitively helped me and put me on the right way, I should be able to manage this now! :)
    – Casper Oct 12 '14 at 11:35
0

got bored. this is not for internet points.

<?php  
// create table user (userid int auto_increment primary key, username varchar(60), password varchar(60)); 
// alter table user add constraint uc_user_username unique (username); 

var_dump($_POST); 

$user   = isset($_POST['username'])    ? trim($_POST['username'])  : ''; 
$pass   = isset($_POST['password'])    ? trim($_POST['password'])  : ''; 
$pass2  = isset($_POST['confirm'])     ? trim($_POST['password2']) : ''; 
$action = isset($_POST['action_type']) ? $_POST['action_type']     : ''; 


if (empty($_POST)) {
   // nothing posted 
}
else {
   if (empty($user)) {
      error('you did not provide a username');
   }
   elseif (empty($pass)) {
      error('you did not provide a password');
   }
   else {
      $mysqli = mysqli_connect('localhost','root','','test')
                  or die('Error ' . mysqli_error($link));   

      if ($action=='new_user') {  
         $userdata = get_user_info($mysqli,$user);  
         if ($userdata) {  
            error('user already exists');  
         }
         else { 
            $validpass = validate_password($pass);  
            if ($validpass && $pass==$pass2){ 
               if (make_new_user($mysqli,$user,$pass)) {
                  print "<br/>new user created<br/><br/>"; 
               }   
            }
            else error('passwords did not match');
         } 
      }
      elseif ($action=='login_user') {  
         $verified  = verify_credentials($mysqli,$user,$pass);
         if ($verified) {
            print "<br/>user logged in<br/><br/>"; 
         } 
      }   
      elseif ($action=='update_pass') {
         $verified  = verify_credentials($mysqli,$user,$pass);
         $validpass = validate_password($pass); 
         if ($verified && $validpass && $pass!=$pass2) { 
            if (update_password($mysqli,$user,$pass,$pass2)) {
               print "<br/>new user created<br/><br/>"; 
            }  
         } 
         else error('cannot update to same password'); 
      } 
      $mysqli->close(); 
   } 
}

function error($message) {
   print "<br/>$message<br/><br/>";
}

function update_password($mysqli,$user,$pass,$pass2) { 
   $hash = password_hash($pass, PASSWORD_BCRYPT);     
   $stmt = $mysqli->prepare('update user set password = ? where username = ?');
   $stmt->bind_param('ss',$user,$hash);
   $stmt->execute(); 
   $msql_error = $mysqli->error; 
   $updated = !(empty($msql_error));

   error($msql_error);  // for debugging only

   return $updated;  
}

function make_new_user($mysqli,$user,$pass) {
   $userid = false;   
   $hash = password_hash($pass, PASSWORD_BCRYPT);   
   $stmt = $mysqli->prepare('insert into user (username,password) values (?,?)');
   $stmt->bind_param('ss',$user,$hash);
   $stmt->execute(); 
   $msql_error = $mysqli->error; 
   if (empty($msql_error)) {
      $userid = $mysqli->insert_id;
   } 
   else error($msql_error);  // for debugging only
   return $userid; 
}

// really, this should be done with javascript instantaneously 
function validate_password($pass) { 
   $error = false; 
   if (strlen($pass) < 8) {
      error('please enter a password with at least 8 characters');
   }
   elseif (!preg_match('`[A-Z]`', $pass)) {
      error('please enter at least 1 capital letter');
   } 
   else $error = true; 
   return $error;
}

function verify_credentials($mysqli,$user,$pass) {   
   $row = get_user_info($mysqli,$user);  
   $verified = false; 
   if ($row) { 
      if (password_verify($pass, $row['pass'])) {   
         $verified = true; 
      } 
   }   
   else error('username and password did not match'); 
   return $verified; 
} 

function get_user_info($mysqli,$user) {
   $row = array();  
   $stmt = $mysqli->prepare('select userid, username, password 
                             from   user 
                             where  username = ?');
   $stmt->bind_param('s',$user);
   $stmt->execute();
   $stmt->bind_result($row['userid'],$row['user'],$row['pass']);
   if (!$stmt->fetch()) $row = false;  
   $stmt->close();  
   return $row;  
}
?>

<body>
   <form action='?' method='post'>
      <table id='input_table'>  
         <tr><td><span>username </span></td><td><input id='username' name='username' type='text' value='<?php echo $user ?>'></td></tr>
         <tr><td><span>password </span></td><td><input id='password' name='password' type='text' value='<?php echo $pass ?>'></td></tr>
         <tr><td><span>password2</span></td><td><input id='password2' name='password2' type='text' value='<?php echo $pass2 ?>'></td></tr>
         <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
         <tr><td colspan=2>this just picks the action for testing... you wouldn't keep it around</td></tr>
         <tr><td><input type='radio' name='action_type' value='new_user'    <?php echo $action=='new_user'?'checked':'' ?>>New User</td></tr>
         <tr><td><input type='radio' name='action_type' value='login_user'  <?php echo $action=='login_user'?'checked':'' ?>>Logging In</td></tr>
         <tr><td><input type='radio' name='action_type' value='update_pass' <?php echo $action=='update_pass'?'checked':'' ?>>New Password</td></tr>
         <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
         <tr><td colspan=2><input id='submit' name='submit' type='submit'/></td></tr>
   </form>
</body>
gloomy.penguin
  • 5,833
  • 6
  • 33
  • 59
-1
// error = 0  means no error found you can continue to upload...
if ($_FILES['file']['error'] == 0) {

}

Here are all of the errors explained: http://php.net/manual/en/features.file-upload.errors.php

UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.

To validate input fields

if(empty($_POST['name'])&&empty($_POST['password'])){
 //fields empty show error here
}else if (is_numeric($username[0])){
    echo 'First character must be a letter';
}
else if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) {
     echo 'Only letters and numbers are allowed';
}else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     echo 'Invalid email address.'; 
}else if(!preg_match("/^[\pL\s,.'-]+$/u", $name)) {
     echo 'Invalid name.'; 
}
Sparsh
  • 301
  • 3
  • 9
  • This only applies to files that you upload, or am I missing something? I want a user to input their information into a registration form using and check the input for errors. – Casper Oct 12 '14 at 01:15
  • OK you saying you want to validate all input fields instead of file upload? – Sparsh Oct 12 '14 at 01:22
  • Yes, correct! I'm having a registration form and I'm trying to validate the data the user inputs and if it all turns out correct with no errors move on to the $query part. – Casper Oct 12 '14 at 01:24
  • Hmm, that is one way of doing it (I tried it and got a working example) but if there are several errors (example: no username and passwords are not matching) it will only display the first one, in this case "No username error". I think that I can store the errors in a array and after that print them out, or maybe not, because the code is stopping after the "else if" statement. Any further tips on the part of displaying ALL errors? If not, thank you anyways, you put me on the correct track! – Casper Oct 12 '14 at 01:49
  • if you are new you can watch tutorials here : https://www.youtube.com/playlist?list=PLE134D877783367C7 please accept if you like the answer – Sparsh Oct 12 '14 at 02:07
  • Took a quick look and it seems to be what I'm looking for(video 14-18), will dig deeper into it tomorrow! Thank you for your help! – Casper Oct 12 '14 at 02:11
  • Did I miss something? What is the relevance of file uploads? – James Oct 12 '14 at 14:28