0

I make a home page which hava a button for user to login or go to profile.

I wish the button have a funtion like this: When login, the button will show username and if click will bring user to profile page. When not login, the button will show login/regiater and if click will bring user to login page.

The homepage button:

<a href="login.php" class="get-started-btn">
  <?php if (mysqli_num_rows($result) == 1 ){
                //log user in
                $_SESSION["user_id"] = $id['user_id'];
                echo $username;
                //here put profile.php
            }else{
                echo "登入/注册"; //login/register
                //here put login.php 
            } ?>
</a>

The login/register_server php:

$username = '';
$email = '';
$password = '';
$errors = array();
        
//connect to the database
$db = mysqli_connect('localhost', 'root', '', 'hdhouse');

//If register button is clicked
if (isset($_POST['register'])) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

        $user_check_query = "SELECT * FROM user WHERE email='$email' LIMIT 1";
        $check = mysqli_query($db, $user_check_query);
        $user = mysqli_fetch_assoc($check);

        if ($user) { // if user exists

          if ($user['email'] === $email) {
            array_push($errors, "email already exists");
          }
        }
    
   //To make sure that form are filled
    if(empty($username)){
        array_push($errors, "Username is Required!");
    }
    if(empty($email)){
        array_push($errors, "Email is Required!");
    }
    if(empty($password)){
        array_push($errors, "Password is Required!");
    }else{
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            array_push($errors, "Invalid email format");

    }
    if(!isset($_POST['term_check'])){
        array_push($errors, "Please check the terms & conditions!");
      } else {
        // nothing
      }//If there are no error, save the user info to database
    if(count($errors) == 0){
        //encrypt password before stroing into database
        $password = ($password);
        
        $sql = "INSERT INTO user (username, email, password) 
        VALUES ('$username', '$email', '$password')";
        mysqli_query($db, $sql);
        $_SESSION['success'] = "Register Success!";
        header('location: login.php');
    }
}
//log user in from login page
if(isset($_POST['login'])) {
    $username = $_POST["username"];
    $password = $_POST["password"];
    
   //To make sure that form are filled
    if(empty($username)){
        array_push($errors, "Userame is Required!");
    }
    if(empty($password)){
        array_push($errors, "Password is Required!");
    }
    
    if(count($errors) == 0){
        $password =($password); //compare the password form database
        $query = "SELECT * FROM user WHERE username ='$username' and password ='$password'";
        $result = mysqli_query($db, $query);
        $id = mysqli_fetch_array($result);
        if (mysqli_num_rows($result) == 1 ){
            //log user in
            $_SESSION["user_id"] = $id['user_id'];
            header('location: 主页.php'); //home.php

        }else{
            array_push($errors, "Wrong Username or Password!");
        }
    }
}
MarioG8
  • 5,122
  • 4
  • 13
  • 29
Hui74433
  • 1
  • 2
  • And what is the issue specifically? – mplungjan Dec 17 '21 at 08:37
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Dec 17 '21 at 09:16
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. – ADyson Dec 17 '21 at 09:16
  • Never configure your web app to login to the database as `root`. Root can do whatever it likes, so on top of the SQL injection vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually _needs_ in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup. – ADyson Dec 17 '21 at 09:16
  • Also, please don't store passwords in plain text - that is another security risk. Learn about [password hashing](https://www.php.net/manual/en/faq.passwords.php) instead. – ADyson Dec 17 '21 at 09:16

1 Answers1

-1

When you are rendering the button, you can check the relevant Session value to see if the user is logged in or not.

Something like this, for example:

<?php 
if (isset($_SESSION["user_id")) {
  echo '<a href="login.php" class="get-started-btn">Log in</a>';
}
else
{
  echo '<a href="profile.php" class="get-started-btn">View Your Profile</a>';
}
ADyson
  • 57,178
  • 14
  • 51
  • 63