• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 565
  • Last Modified:

auth using php realm with mysql

i want to use apache realm aut but not with .htacess and .htpasswd but with mysql so that it will auth the user by checking the username and password againiest mysql database.....how can i do this???
0
neutrongenious
Asked:
neutrongenious
  • 2
  • 2
1 Solution
 
RoonaanCommented:
Well php auth is quite "easy" to write yourself:

<?php
  $authorized = false;
 
  mysql_connect('fill','this','fields')
    or die('No db connection');
  mysql_select_db('some database')
    or die('No db connection');

  if(!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW']))
  {
    $username = mysql_real_escape_string($_SERVER['PHP_AUTH_USER']);
    $password = mysql_real_escape_string($_SERVER['PHP_AUTH_PW']);
   
   
    $query = "SELECT id FROM usertable WHERE".
             " `username` = '$username' AND".
             " `password` = '$password' LIMIT 1";
   
    $result = mysql_query($query);
    if(!mysql_error())
      $authorized = (mysql_num_rows($result) == 1);
  }
 
  if(!$authorized)
  {
    Header('WWW-Authenticate: Basic realm="My Websites Realm" ');
    Header("HTTP/1.0 401 Unauthorized");
    echo "Action cancelled: Try again";
    exit();
  }
?>

-r-
0
 
neutrongeniousAuthor Commented:
thanks for the reply it works fine.
now tell me i want to use this user's info in some areas how can i use them....
should i store them in a session or what?????
and what if i want to provide that user logoff info....
0
 
RoonaanCommented:
Yes, you would store such data in a session.

Add <?php session_start();?> as the first line of code, and you can store and retrieve anything you want in and from the $_SESSION array.

I am not sure wether or not you can unset($_SESSION['PHP_AUTH_USER']) but then again, you could have a go at it. Otherwise you have to add some additional code, which makes your session invalid when someone tries to login.

-r-
0
 
neutrongeniousAuthor Commented:
thanks this solves my problem
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now