-2

So, i am learning how to write php now.I want to build a small shopping website. My index.html looks something like this:

<!DOCTYPE html>
<html>
  <head>
    <link href="index.css" rel="stylesheet" />
      <title>
        eShop
      </title>
  </head>
  <body>
    <div class="topnav">
      <a class="active" href="#index.html">Home</a>
      <a href="loginAdmin.php">Administrator</a>
      <a href="loginUser.php">Register User</a>
      <a href="newAccount.php">Register New Account</a>
    </div>
    <img class="centerImage" src="eshop.jpg">
 </body>
</html>

and the loginAdmin.php file looks like this:

<?php
session_start();
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";

$link = mysqli_connect(localhost,$user,$passwd);
@mysqli_select_db($link,$database) or die ("Unable to select database");

// try to create a new record from the submission
$username =  mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);

if ($username && $password) {

  // here we define the SQL command
  $query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";

  // submit the query to the database
  $res=mysqli_query($query);

  // make sure it worked!
  if (!$res) {
    echo mysql_error();
    exit;
  }

  // find out how many records we got
  $num = mysqli_numrows($res);

  if ($num==0) {
    echo "<h3>Invalid login</h3>\n";
    exit;
  } elseif ($num!=1) {
    echo "<h3>Error - unexpected result!\n";
    exit;
  }

  // valid login, set the session variable
  $_SESSION['userid']=mysql_result($res,0,'userid');
  echo "<h3>Welcome $username</h3>\n";
?>

<head>
    <link href="login.css" rel="stylesheet" />
    <title>
        eShop
    </title>
</head>

<body>
    <div class="login-page">
        <div class="form">
            <form class="login-form">
                <input type="text" placeholder="User Name:" />
                <input type="password" placeholder="Password:" />
                <button onclick="writeMsg()">login</button>
            </form>
        </div>
    </div>
</body>

If the user pressed on the loginAdmin link so the php code will be executed, and i dont want that, only after the user pressed on the login button i want the php code block will be executed. How can i do that? Maybe i should seperate the files (php and html) and not user href on the php files in the index.html ? and the index.html file should be index.php?

  • You need to give the inputs names (eg 'username') and should then check if `$_POST['username']` (or $_REQUEST, but I'd prefer to be precice) is set (like `isset($_POST['username']`) -> then execute what you need, else just display the form – Jeff Jun 21 '17 at 19:19
  • well the proper way to do this its by using sessions for authenticated users. Then check with condition if user session exists in order to show more content. – Leo Jun 21 '17 at 19:19
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jun 21 '17 at 20:45
  • **Never store plain text passwords!** Please use ***PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html)*** to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). ***It is not necessary to [escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Jun 21 '17 at 20:45
  • `mysqli_connect()` will fail - no default database supplied. – Jay Blanchard Jun 21 '17 at 20:46
  • You're suppressing errors by using `@`. You shouldn't do that, you should catch and handle errors properly. – Jay Blanchard Jun 21 '17 at 20:47
  • `mysqli_query()` will not work without a connection. – Jay Blanchard Jun 21 '17 at 20:48
  • `mysql_error()` will not work with `mysqli` definitions. – Jay Blanchard Jun 21 '17 at 20:48
  • Same with `mysql_result()` – Jay Blanchard Jun 21 '17 at 20:49
  • There are 7 errors in this posted code. – Funk Forty Niner Jun 21 '17 at 20:49

1 Answers1

-1

You need to add your php code within a condition which satisfies when the form submission happens. Also you need to add name to your input fields

Your code will look like this,

<?php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) { //Added this line
    // here is the code that connects to the database. Note that the username
    // and password are "hard-coded".
    $user="root";
    $passwd="";
    $database="";

    $link = mysqli_connect(localhost,$user,$passwd);
    @mysqli_select_db($link,$database) or die ("Unable to select database");

    // try to create a new record from the submission
    $username =  mysqli_real_escape_string($link,$_REQUEST['username']);
    $password= mysqli_real_escape_string($link,$_REQUEST['password']);

    if ($username && $password) {

        // here we define the SQL command
        $query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";

        // submit the query to the database
        $res=mysqli_query($query);

        // make sure it worked!
        if (!$res) {
            echo mysql_error();
            exit;
        }

        // find out how many records we got
        $num = mysqli_numrows($res);

        if ($num==0) {
            echo "<h3>Invalid login</h3>\n";
            exit;
        } elseif ($num!=1) {
            echo "<h3>Error - unexpected result!\n";
            exit;
        }

        // valid login, set the session variable
        $_SESSION['userid']=mysql_result($res,0,'userid');
        echo "<h3>Welcome $username</h3>\n";
    }
} //Added this line
?>

<head>
    <link href="login.css" rel="stylesheet" />
    <title>
        eShop
    </title>
</head>

<body>
    <div class="login-page">
        <div class="form">
            <form class="login-form" method="POST"> <!-- edited this line -->
                <input type="text" name="username" placeholder="User Name:" /> <!-- edited this line -->
                <input type="password" name="password" placeholder="Password:" /> <!-- edited this line -->
                <button onclick="writeMsg()">login</button>
            </form>
        </div>
    </div>
</body>

I have just added name to the form fields & then kept all your PHP code within a condition

manian
  • 1,418
  • 2
  • 16
  • 32
  • 1
    Turn the tide against teaching/propagating sloppy and dangerous coding practices. If you post an answer without prepared statements [you may want to consider this before posting](http://meta.stackoverflow.com/q/344703/). Additionally [a more valuable answer comes from showing the OP the right method](https://meta.stackoverflow.com/a/290789/1011527). – Jay Blanchard Jun 21 '17 at 20:44
  • There are 5 errors in this answer. 6 if you count having echo'd stuff outside the HTML markup. – Funk Forty Niner Jun 21 '17 at 20:48
  • @JayBlanchard, since the OP is a beginner, I didn't want to put too many things. But yes, I will update my answer & also will consider your note in my future answers. Thanks for mentioning anyways. – manian Jun 21 '17 at 20:48
  • 1
    You put all of the things or you don't put them at all @manian. It does no service to the OP if you leave things out and they still have failures and unsafe code. – Jay Blanchard Jun 21 '17 at 20:50
  • @Fred-ii-, I just wanted to fix OP's problem. I will update my answer with better solution – manian Jun 21 '17 at 20:50
  • You didn't fix the OP's problems at all. Look at my comments under the OP's question. – Jay Blanchard Jun 21 '17 at 20:50
  • Sure @JayBlanchard, I will review my answer & update – manian Jun 21 '17 at 20:51