Contents / Previous / Next


Example: User Log IN

This example implements a login form, checked via a table from a PostgreSQL database.
Students may log in with their name and give their id as "password".
If the login is correct the stud table from the workshop database is printed:

Source (BW):

<?php

function print_form() 
{
echo 
" <P>Please log in with name and id:<P>";
echo <<<form_text_region
    
  <form ACTION=$_SERVER
[PHP_SELF] METHOD="POST">
     Your name: <INPUT TYPE="text" NAME="name" /><p>
     Your id:   <INPUT TYPE="password" NAME="id" /><p>
     <INPUT TYPE=hidden NAME="sent_from_my_org_form" VALUE=23>
     <INPUT TYPE="submit">
  </form>
  
form_text_region;
}


function 
check_form() 
{
  if( !isset(
$_POST[name]) || empty($_POST[name]) ||
      !isset(
$_POST[id]) || $_POST[id]<|| 
      !isset(
$_POST[sent_from_my_org_form]) || 
             
$_POST[sent_from_my_org_form]!=23 )
  {
    echo 
"<P><CENTER><H2>Please log in</H2></CENTER><P>";
    
print_form();
    return 
FALSE;  
  }
  else { return 
TRUE; }
}

function 
check_login() 
{
  global 
$_POST$dbh;
  
  
// Hardcoded password.
  //if( $_POST[name]=="me" && $_POST[id]=="1" )

  
$con "dbname=workshop user=felix";
  
$dbh pg_connect$con );
  if( ! 
$dbh 
  {  
    echo 
"Connection error!<BR>\n"
    exit(
1);
  }
  
$query_str"SELECT id FROM stud WHERE name='$_POST[name]';";
  
//echo '$query_str='.$query_str;
  
$res pg_query$dbh$query_str );
  if( ! 
$res || pg_num_rows$res ) != || pg_num_fields$res ) != 
  {
    echo 
"DB error!<BR>\n"
    
//exit(1);    
  
}
  
$row pg_fetch_array$res );
  
//print_r( $row );
  //echo "<P>".$_POST[id]."==".$row[id]."<P>";
  
if( $_POST[id]==$row[0] )
  {
    return 
TRUE;  
  }
  else { return 
FALSE; }
}



function 
sorry_try_again() 
{
  echo 
"<P><CENTER><H2><FONT color=red>Sorry,</FONT>
      could not log you in. Try again!</CENTER><P>"
;
  
print_form();
}



//
// main
//

// Database handle:
$dbh;

if ( 
check_form() )
{
  if( 
check_login() )
  {
    echo 
"<H2>Here it is.</H2>";
    echo 
"<P>This are you fellow students:<P>";
    
$result_rows pg_copy_to $dbh"stud" ); 
    if ( ! 
$result_rows ) { echo "No result!<BR>"; return; } 
    foreach( 
$result_rows as $row ) { echo $row."<BR>"; }
  }
  else 
  { 
    
sorry_try_again(); 
  }
}

?>