| re: Fetch password protected data in PHP
Maybe this one can be of some help. It shows a html screen asking for userid and password. When submitted it goes to the database and checks the existence of the userid/password (SHA1 encrypted) in the db record. All you have to change is the MySql statement, because it uses some db interface I used to use. Here is the code followed by the logout routine.
[php]
LOGIN.PHP routine
------------------
<?php
session_start();
if (array_key_exists('username', $_SESSION)) {
process_form(1);
}
else {
if ($_POST['_submit_check']) {
if ($form_errors = validate_form()) {
show_form($form_errors);
}
else {
process_form(0);
}
}
else {
show_form();
}
}
function show_form($errors = '') {
print '<form name="authForm" method="POST" action="'.$_SERVER['PHP_SELF'].'">';
if ($errors) {
print '<span style="color:red"><ul><li><b>';
print implode('</b></li><li><b>',$errors);
print '</b></li></ul></span>';
}
print 'Username';
print '<input type="text" name="username" value="';
print htmlentities($_POST[username]) . '"> <br />';
print 'Password';
print '<input type="password" name="password" value="';
print htmlentities($_POST[password]) . '"> <br />';
print '<input type="submit" name="login" value="Login" />';
print '<input type="hidden" name="_submit_check" value="1"/>';
print '</form>';
print '<a href="index.php">Click</a> here if you want to leave this form.';
}
function validate_form() {
$errors = array();
$userid=$_POST['username'];
$passwd=$_POST['password'];
/************************************************** **************************
* Check username and password in database *
************************************************** **************************/
// ..... connect to data base
$text = "";
$text = $db->get_var("SELECT * FROM authorized_users WHERE userid='$userid' AND passwd=sha1('$passwd')") ;
if ($text == "") {
$errors[] = 'Enter a valid username and password!';
}
return $errors;
}
function process_form($logged_in) {
if ($logged_in == 0) {
// Add the username to the session
$_SESSION['username'] = $_POST['username'];
}
print 'You are logged in as: <b>'.$_SESSION['username'].'</b>'.str_repeat(' ', 10).'<a href="logout.php">Logout</a><br />';
print '<p>You can continue processing as a logged-in user ............</p>';
}
?>
LOGOUT.PHP routine:
-------------------
<?php
session_start();
unset($_SESSION['username']);
print '<p>You are logged out.</p>';
?>
[/php]
Ronald :cool:
|