login method in php code example
Example 1: simple login form in php
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if(!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if($validUser) {
header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<form name="input" action="" method="post">
<label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
<label for="password">Password:</label><input type="password" value="" id="password" name="password" />
<div class="error"><?= $errorMsg ?></div>
<input type="submit" value="Home" name="sub" />
</form>
</body>
</html>
Example 2: php login form
<?php
define('DB_SERVER', 'localhost:3036');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'rootpassword');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>