Exercise : Login (by Morgan Doocy)

Write a form, login.html, which asks the user for a username and password. Then write a script, login.php, that will look in the file passwd.txt to see if the user's password matches. Each username/password pair will be stored on its own line in the form username:password.

If the password entered matches the password stored in the file for that user, login.php should display a message with a class of granted. Otherwise, it should display a message with a class of denied.

If the user checks "I'm a new user", then you should add the provided username and password to passwd.txt.

Exercise : Login (by Morgan Doocy)

screenshot of login.html filled out screenshot of login.php with access granted

Exercise Solution

<!DOCTYPE html>
<html>
	<head>
		<title>Login</title>
		<link href="http://webster.cs.washington.edu/cse154/sections/4/login/login.css" type="text/css" rel="stylesheet" />
	</head>
	<body>
		<h1>Login</h1>
		<form action="login.php" method="post">
			<dl>
				<dt>Username:</dt>
				<dd><input type="text" name="username" /></dd>
				<dt>Password:</dt>
				<dd><input type="password" name="password" /></dd>
			</dl>
			<p><label><input type="checkbox" name="new" /> I am a new user.</label></p>
			<p><input type="submit" value="Log in" /></p>
		</form>
	</body>
</html>

Exercise Solution

<?php
$user = $_POST["username"];
$passwd = $_POST["password"];
$new = isset($_POST["new"]);
if ($new) {
	file_put_contents("passwd.txt", "$user:$passwd\n", FILE_APPEND);
} else {
	$granted = false;
	$passwords = explode("\n", file_get_contents("passwd.txt"));
	foreach ($passwords as $line) {
		list($stored_user, $stored_pass) = explode(":", $line);
		if ($entered_user == $stored_user
				&& $entered_pass == $stored_pass) {
			$granted = true;
			break;
		}
	}
}
?>

Exercise Solution

<!DOCTYPE html>
<html>
	<head>
	<title>Login</title>
	<link rel="stylesheet" type="text/css"
		href="http://webster.cs.washington.edu/cse154/sections/4/login/login.css" />
	</head>
	<body>
		<?php if ($new) { ?>
			<h1 class="granted">Welcome, <?= $entered_user ?>!</h1>
		<?php } else if ($granted) { ?>
			<h1 class="granted">Access granted</h1>
		<?php } else { ?>
			<h1 class="denied">Access denied!</h1>
		<?php } ?>
	</body>
</html>