Simple password protection in PHP

Chilster

New Member
I was reading a quite interesting chapter in a "Learning PHP"-book of mine and came across a code example which I wanted to modify and use on my personal website (to protect a simple document, nothing "big", which is why I also don't encrypt the passwords).I've used the php-sample and I just can't make it work at all.
Here it is (dont get scared by the length, it's really simple):\[code\]<?phpif ($_POST['_submit_check']) { if ($form_errors = validate_form()) { show_form($form_errors); } else { process_form(); }} else { show_form();}function show_form($errors = '') { echo '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '">'; if ($errors) { echo '<br>' echo implode('<br>', $errors); echo '<br>'; } echo 'Username: '; echo '<input type="text" name="username" value="http://stackoverflow.com/questions/3676968/Username goes here">'; echo '<br>' echo 'Password: '; echo '<input type="password" name="password">'; echo '<br>' echo '<input type="submit" name="submit" value="http://stackoverflow.com/questions/3676968/Log In">'; echo '<input type="hidden" name="_submit_check" value="http://stackoverflow.com/questions/3676968/1">'; //when the form is entered, this returns true and the first line of the document is good to go echo '</form>';}function validate_form() { $errors = array(); $users = array('admin' => 'pass123', 'notsoadmin' => 'pass1234'); if (!array_key_exists($_POST['username']) { $errors[] = "Please enter username and password"; } $saved_password = $users[ $_POST['password'] ]; if ($saved_password != $_POST['password']) { echo "Password and username don't match. Please try again"; } return $errors;}function process_form() { $_SESSION['username'] = $_POST['username']; echo "Welcome, $_SESSION[username]";}?>\[/code\]Before my HTML and stuff I also added this:\[code\]<?php session_start(); ?>\[/code\]Clearly I've missed something... Maybe it's \[code\]$form_errors\[/code\] right at the beginning, that causes the problem (which is "nothing happens"), it was in my book but I'm not sure why/where it comes from?
 
Back
Top