PHP - First Login System

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
5
down vote

favorite












I am quite new to PHP, and with the help of a few tutorials have made this login system.



However I know its not as efficient and compact as it could be, also I am looking for ways to improve the security of this system. As I noticed when testing that If I simply changed the url from the login page, I could bypass the whole login process without having to login. I'm not really sure how I would go about fixing this, I tried creating session variables at the bottom of the script but not really sure if this is the way to go about it.



I would be very grateful for any feedback and if someone could help me improve this code, to make it more secure and maybe more efficient?



<?php

session_start();

if (isset($_POST['submit']))

require_once 'config.php';

$username = mysqli_real_escape_string($connect, $_POST['username']);
$password = mysqli_real_escape_string($connect, $_POST['password']);

//Error handlers
//Check if inputs are empty
if (empty($username) else
header("Location: ../index.php?login=error");
exit();

?>






share|improve this question



























    up vote
    5
    down vote

    favorite












    I am quite new to PHP, and with the help of a few tutorials have made this login system.



    However I know its not as efficient and compact as it could be, also I am looking for ways to improve the security of this system. As I noticed when testing that If I simply changed the url from the login page, I could bypass the whole login process without having to login. I'm not really sure how I would go about fixing this, I tried creating session variables at the bottom of the script but not really sure if this is the way to go about it.



    I would be very grateful for any feedback and if someone could help me improve this code, to make it more secure and maybe more efficient?



    <?php

    session_start();

    if (isset($_POST['submit']))

    require_once 'config.php';

    $username = mysqli_real_escape_string($connect, $_POST['username']);
    $password = mysqli_real_escape_string($connect, $_POST['password']);

    //Error handlers
    //Check if inputs are empty
    if (empty($username) else
    header("Location: ../index.php?login=error");
    exit();

    ?>






    share|improve this question























      up vote
      5
      down vote

      favorite









      up vote
      5
      down vote

      favorite











      I am quite new to PHP, and with the help of a few tutorials have made this login system.



      However I know its not as efficient and compact as it could be, also I am looking for ways to improve the security of this system. As I noticed when testing that If I simply changed the url from the login page, I could bypass the whole login process without having to login. I'm not really sure how I would go about fixing this, I tried creating session variables at the bottom of the script but not really sure if this is the way to go about it.



      I would be very grateful for any feedback and if someone could help me improve this code, to make it more secure and maybe more efficient?



      <?php

      session_start();

      if (isset($_POST['submit']))

      require_once 'config.php';

      $username = mysqli_real_escape_string($connect, $_POST['username']);
      $password = mysqli_real_escape_string($connect, $_POST['password']);

      //Error handlers
      //Check if inputs are empty
      if (empty($username) else
      header("Location: ../index.php?login=error");
      exit();

      ?>






      share|improve this question













      I am quite new to PHP, and with the help of a few tutorials have made this login system.



      However I know its not as efficient and compact as it could be, also I am looking for ways to improve the security of this system. As I noticed when testing that If I simply changed the url from the login page, I could bypass the whole login process without having to login. I'm not really sure how I would go about fixing this, I tried creating session variables at the bottom of the script but not really sure if this is the way to go about it.



      I would be very grateful for any feedback and if someone could help me improve this code, to make it more secure and maybe more efficient?



      <?php

      session_start();

      if (isset($_POST['submit']))

      require_once 'config.php';

      $username = mysqli_real_escape_string($connect, $_POST['username']);
      $password = mysqli_real_escape_string($connect, $_POST['password']);

      //Error handlers
      //Check if inputs are empty
      if (empty($username) else
      header("Location: ../index.php?login=error");
      exit();

      ?>








      share|improve this question












      share|improve this question




      share|improve this question








      edited Feb 9 at 20:21









      200_success

      123k14143401




      123k14143401









      asked Feb 9 at 18:14









      TessRay97

      282




      282




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          5
          down vote



          accepted










          Security



          You are escaping user input, which prevents SQL injection. It's good enough, but really not the recommended way to do this as it's too error-prone (whenever a project does this, it's basically guaranteed that you can find injections). Use prepared statements instead. It's not only more secure, but also leads to nicer code.



          Guard Clauses



          You have a lot of nested ifs, which makes it difficult to see what happens when (for example, I have to scroll all the way down to see what happens if it's a GET request).



          If you use guard clauses / return early instead, your code will be much more readable. It might look like this:



          if (!isset($_POST['submit'])) 
          header("Location: ../index.php?login=error");
          exit();


          if (empty($username) || empty($password))
          header("Location: ../index.php?login=empty");
          exit();


          // select the user

          if (!$userExists)
          header("Location: ../index.php?login=error");
          exit();


          // verify the password

          if ($validPassword)
          header("Location: ../index.php?login=error");
          exit();


          // set the session, redirect


          Now it's very clear what happens when.



          Duplication and functions



          Following a header redirect with exit is very good practice. You can make sure that you always do this, simplify the code, and make it easier to modify later by extracting that to it's own function (eg redirectError(Error error)).



          True or false



          Something is either true or false. There is no reason to do an else check on true if you already did one on false.



          Note though that some equals checks can be unexpected, so you should always use strong comparison (===) if you don't have a reason not to.






          share|improve this answer





















          • Thank you for the feedback, it really helps! just a few questions with the guard clauses, with the $userexists and $validpassword can I just re-arrange my code to create those two variables, or would I have to create seperate code for those two variables if that makes any sense?
            – TessRay97
            Feb 9 at 20:49










          • @TessRay97 Yes, you can just re-arrange the code if you want to (the comments I placed are basically placeholders for the code you had in place already). You could also crease functions for them instead (which I would prefer because it's reusable, easier to maintain, and nicer to read) and/or follow different paradigms (eg OOP).
            – tim
            Feb 9 at 21:00










          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f187203%2fphp-first-login-system%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          5
          down vote



          accepted










          Security



          You are escaping user input, which prevents SQL injection. It's good enough, but really not the recommended way to do this as it's too error-prone (whenever a project does this, it's basically guaranteed that you can find injections). Use prepared statements instead. It's not only more secure, but also leads to nicer code.



          Guard Clauses



          You have a lot of nested ifs, which makes it difficult to see what happens when (for example, I have to scroll all the way down to see what happens if it's a GET request).



          If you use guard clauses / return early instead, your code will be much more readable. It might look like this:



          if (!isset($_POST['submit'])) 
          header("Location: ../index.php?login=error");
          exit();


          if (empty($username) || empty($password))
          header("Location: ../index.php?login=empty");
          exit();


          // select the user

          if (!$userExists)
          header("Location: ../index.php?login=error");
          exit();


          // verify the password

          if ($validPassword)
          header("Location: ../index.php?login=error");
          exit();


          // set the session, redirect


          Now it's very clear what happens when.



          Duplication and functions



          Following a header redirect with exit is very good practice. You can make sure that you always do this, simplify the code, and make it easier to modify later by extracting that to it's own function (eg redirectError(Error error)).



          True or false



          Something is either true or false. There is no reason to do an else check on true if you already did one on false.



          Note though that some equals checks can be unexpected, so you should always use strong comparison (===) if you don't have a reason not to.






          share|improve this answer





















          • Thank you for the feedback, it really helps! just a few questions with the guard clauses, with the $userexists and $validpassword can I just re-arrange my code to create those two variables, or would I have to create seperate code for those two variables if that makes any sense?
            – TessRay97
            Feb 9 at 20:49










          • @TessRay97 Yes, you can just re-arrange the code if you want to (the comments I placed are basically placeholders for the code you had in place already). You could also crease functions for them instead (which I would prefer because it's reusable, easier to maintain, and nicer to read) and/or follow different paradigms (eg OOP).
            – tim
            Feb 9 at 21:00














          up vote
          5
          down vote



          accepted










          Security



          You are escaping user input, which prevents SQL injection. It's good enough, but really not the recommended way to do this as it's too error-prone (whenever a project does this, it's basically guaranteed that you can find injections). Use prepared statements instead. It's not only more secure, but also leads to nicer code.



          Guard Clauses



          You have a lot of nested ifs, which makes it difficult to see what happens when (for example, I have to scroll all the way down to see what happens if it's a GET request).



          If you use guard clauses / return early instead, your code will be much more readable. It might look like this:



          if (!isset($_POST['submit'])) 
          header("Location: ../index.php?login=error");
          exit();


          if (empty($username) || empty($password))
          header("Location: ../index.php?login=empty");
          exit();


          // select the user

          if (!$userExists)
          header("Location: ../index.php?login=error");
          exit();


          // verify the password

          if ($validPassword)
          header("Location: ../index.php?login=error");
          exit();


          // set the session, redirect


          Now it's very clear what happens when.



          Duplication and functions



          Following a header redirect with exit is very good practice. You can make sure that you always do this, simplify the code, and make it easier to modify later by extracting that to it's own function (eg redirectError(Error error)).



          True or false



          Something is either true or false. There is no reason to do an else check on true if you already did one on false.



          Note though that some equals checks can be unexpected, so you should always use strong comparison (===) if you don't have a reason not to.






          share|improve this answer





















          • Thank you for the feedback, it really helps! just a few questions with the guard clauses, with the $userexists and $validpassword can I just re-arrange my code to create those two variables, or would I have to create seperate code for those two variables if that makes any sense?
            – TessRay97
            Feb 9 at 20:49










          • @TessRay97 Yes, you can just re-arrange the code if you want to (the comments I placed are basically placeholders for the code you had in place already). You could also crease functions for them instead (which I would prefer because it's reusable, easier to maintain, and nicer to read) and/or follow different paradigms (eg OOP).
            – tim
            Feb 9 at 21:00












          up vote
          5
          down vote



          accepted







          up vote
          5
          down vote



          accepted






          Security



          You are escaping user input, which prevents SQL injection. It's good enough, but really not the recommended way to do this as it's too error-prone (whenever a project does this, it's basically guaranteed that you can find injections). Use prepared statements instead. It's not only more secure, but also leads to nicer code.



          Guard Clauses



          You have a lot of nested ifs, which makes it difficult to see what happens when (for example, I have to scroll all the way down to see what happens if it's a GET request).



          If you use guard clauses / return early instead, your code will be much more readable. It might look like this:



          if (!isset($_POST['submit'])) 
          header("Location: ../index.php?login=error");
          exit();


          if (empty($username) || empty($password))
          header("Location: ../index.php?login=empty");
          exit();


          // select the user

          if (!$userExists)
          header("Location: ../index.php?login=error");
          exit();


          // verify the password

          if ($validPassword)
          header("Location: ../index.php?login=error");
          exit();


          // set the session, redirect


          Now it's very clear what happens when.



          Duplication and functions



          Following a header redirect with exit is very good practice. You can make sure that you always do this, simplify the code, and make it easier to modify later by extracting that to it's own function (eg redirectError(Error error)).



          True or false



          Something is either true or false. There is no reason to do an else check on true if you already did one on false.



          Note though that some equals checks can be unexpected, so you should always use strong comparison (===) if you don't have a reason not to.






          share|improve this answer













          Security



          You are escaping user input, which prevents SQL injection. It's good enough, but really not the recommended way to do this as it's too error-prone (whenever a project does this, it's basically guaranteed that you can find injections). Use prepared statements instead. It's not only more secure, but also leads to nicer code.



          Guard Clauses



          You have a lot of nested ifs, which makes it difficult to see what happens when (for example, I have to scroll all the way down to see what happens if it's a GET request).



          If you use guard clauses / return early instead, your code will be much more readable. It might look like this:



          if (!isset($_POST['submit'])) 
          header("Location: ../index.php?login=error");
          exit();


          if (empty($username) || empty($password))
          header("Location: ../index.php?login=empty");
          exit();


          // select the user

          if (!$userExists)
          header("Location: ../index.php?login=error");
          exit();


          // verify the password

          if ($validPassword)
          header("Location: ../index.php?login=error");
          exit();


          // set the session, redirect


          Now it's very clear what happens when.



          Duplication and functions



          Following a header redirect with exit is very good practice. You can make sure that you always do this, simplify the code, and make it easier to modify later by extracting that to it's own function (eg redirectError(Error error)).



          True or false



          Something is either true or false. There is no reason to do an else check on true if you already did one on false.



          Note though that some equals checks can be unexpected, so you should always use strong comparison (===) if you don't have a reason not to.







          share|improve this answer













          share|improve this answer



          share|improve this answer











          answered Feb 9 at 20:15









          tim

          24.2k22374




          24.2k22374











          • Thank you for the feedback, it really helps! just a few questions with the guard clauses, with the $userexists and $validpassword can I just re-arrange my code to create those two variables, or would I have to create seperate code for those two variables if that makes any sense?
            – TessRay97
            Feb 9 at 20:49










          • @TessRay97 Yes, you can just re-arrange the code if you want to (the comments I placed are basically placeholders for the code you had in place already). You could also crease functions for them instead (which I would prefer because it's reusable, easier to maintain, and nicer to read) and/or follow different paradigms (eg OOP).
            – tim
            Feb 9 at 21:00
















          • Thank you for the feedback, it really helps! just a few questions with the guard clauses, with the $userexists and $validpassword can I just re-arrange my code to create those two variables, or would I have to create seperate code for those two variables if that makes any sense?
            – TessRay97
            Feb 9 at 20:49










          • @TessRay97 Yes, you can just re-arrange the code if you want to (the comments I placed are basically placeholders for the code you had in place already). You could also crease functions for them instead (which I would prefer because it's reusable, easier to maintain, and nicer to read) and/or follow different paradigms (eg OOP).
            – tim
            Feb 9 at 21:00















          Thank you for the feedback, it really helps! just a few questions with the guard clauses, with the $userexists and $validpassword can I just re-arrange my code to create those two variables, or would I have to create seperate code for those two variables if that makes any sense?
          – TessRay97
          Feb 9 at 20:49




          Thank you for the feedback, it really helps! just a few questions with the guard clauses, with the $userexists and $validpassword can I just re-arrange my code to create those two variables, or would I have to create seperate code for those two variables if that makes any sense?
          – TessRay97
          Feb 9 at 20:49












          @TessRay97 Yes, you can just re-arrange the code if you want to (the comments I placed are basically placeholders for the code you had in place already). You could also crease functions for them instead (which I would prefer because it's reusable, easier to maintain, and nicer to read) and/or follow different paradigms (eg OOP).
          – tim
          Feb 9 at 21:00




          @TessRay97 Yes, you can just re-arrange the code if you want to (the comments I placed are basically placeholders for the code you had in place already). You could also crease functions for them instead (which I would prefer because it's reusable, easier to maintain, and nicer to read) and/or follow different paradigms (eg OOP).
          – tim
          Feb 9 at 21:00












           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f187203%2fphp-first-login-system%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Python Lists

          Aion

          JavaScript Array Iteration Methods