hi guys,

i have a site which is protected using php and stored username and passwords in mysql database.

is there a script which will protect a directory and run off the mysql database username and password as opposed to just a standard htaccess file?

help urgently need for this site.

thanks

Use .htaccess to direct everything to the PHP file. Validate and then display the folder contents using the PHP file.

thanks however my hosting company does not have the mysql auth module installed for htaccess so htaccess is out the question.

i need a script that can protect the directory. it has images and pdf's inside it.

any help please?

Member Avatar for Zagga

Hi mrhankey,

Are you able to move the location of the folder to somewhere above the root level? This way the folder will not be accessible via a browser but your scripts can still access them.

here is a really great script to protect your directory. you can change the
$LOGIN_INFORMATION array to read in all of your records from your db or at least authenticate against that instead of an internally stored list in the script. anyway, I have used this for over a year and never had any problems with it. you just include the script on the page you want to protect.

<?php
include('password_protect.php');  // and that's it.
// rest of your page...

and finally here is password_protect.php

<?php

###############################################################
# Page Password Protect 2.13
###############################################################
# Visit http://www.zubrag.com/scripts/ for updates
############################################################### 
#
# Usage:
# Set usernames / passwords below between SETTINGS START and SETTINGS END.
# Open it in browser with "help" parameter to get the code
# to add to all files being protected. 
#    Example: password_protect.php?help
# Include protection string which it gave you into every file that needs to be protected
#
# Add following HTML code to your page where you want to have logout link
# <a href="http://www.example.com/path/to/protected/page.php?logout=1">Logout</a>
#
###############################################################

/*
-------------------------------------------------------------------
SAMPLE if you only want to request login and password on login form.
Each row represents different user.

$LOGIN_INFORMATION = array(
  'zubrag' => 'root',
  'test' => 'testpass',
  'admin' => 'passwd'
);

--------------------------------------------------------------------
SAMPLE if you only want to request only password on login form.
Note: only passwords are listed

$LOGIN_INFORMATION = array(
  'root',
  'testpass',
  'passwd'
);

--------------------------------------------------------------------
*/

##################################################################
#  SETTINGS START
##################################################################

// Add login/password pairs below, like described above
// fill in the Login_information with the users and passwords from your database.
// NOTE: all rows except last must have comma "," at the end of line
$LOGIN_INFORMATION = array(
  'notadmin' => 'notadmin',
  'admin' => 'admin'
);

// request login? true - show login and password boxes, false - password box only
define('USE_USERNAME', true);

// User will be redirected to this page after logout
define('LOGOUT_URL', 'http://beatricedailysun.com/app/bwoty/');

// time out after NN minutes of inactivity. Set to 0 to not timeout
define('TIMEOUT_MINUTES', 0);

// This parameter is only useful when TIMEOUT_MINUTES is not zero
// true - timeout time from last activity, false - timeout time from login
define('TIMEOUT_CHECK_ACTIVITY', true);

##################################################################
#  SETTINGS END
##################################################################


///////////////////////////////////////////////////////
// do not change code below
///////////////////////////////////////////////////////

// show usage example
if(isset($_GET['help'])) {
  die('Include following code into every page you would like to protect, at the very beginning (first line):<br>&lt;?php include("' . str_replace('\\','\\\\',__FILE__) . '"); ?&gt;');
}

// timeout in seconds
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES * 60);

// logout?
if(isset($_GET['logout'])) {
  setcookie("verify", '', $timeout, '/'); // clear password;
  header('Location: ' . LOGOUT_URL);
  exit();
}

if(!function_exists('showLoginPasswordProtect')) {

// show login form
function showLoginPasswordProtect($error_msg) {
?>
<html>
<head>
  <title>Please enter password to access this page</title>
  <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
  <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</head>
<body>
  <style>
    input { border: 1px solid black; }
  </style>
  <div style="width:500px; margin-left:auto; margin-right:auto; text-align:center">
  <form method="post">
    <h3>Please enter password to access this page</h3>
    <font color="red"><?php echo $error_msg; ?></font><br />
<?php if (USE_USERNAME) echo 'Login:<br /><input type="input" name="access_login" /><br />Password:<br />'; ?>
    <input type="password" name="access_password" /><p></p><input type="submit" name="Submit" value="Submit" />
  </form>
  <br />
  <a style="font-size:9px; color: #B0B0B0; font-family: Verdana, Arial;" href="http://www.zubrag.com/scripts/password-protect.php" title="Download Password Protector">Powered by Password Protect</a>
  </div>
</body>
</html>

<?php
  // stop at this point
  die();
}
}

// user provided password
if (isset($_POST['access_password'])) {

  $login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
  $pass = $_POST['access_password'];
  if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
  || (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) || $LOGIN_INFORMATION[$login] != $pass ) ) 
  ) {
    showLoginPasswordProtect("Incorrect password.");
  }
  else {
    // set cookie if password was validated
    setcookie("verify", md5($login.'%'.$pass), $timeout, '/');
    
    // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
    // So need to clear password protector variables
    unset($_POST['access_login']);
    unset($_POST['access_password']);
    unset($_POST['Submit']);
  }

}

else {

  // check if password cookie is set
  if (!isset($_COOKIE['verify'])) {
    showLoginPasswordProtect("");
  }

  // check if cookie is good
  $found = false;
  foreach($LOGIN_INFORMATION as $key=>$val) {
    $lp = (USE_USERNAME ? $key : '') .'%'.$val;
    if ($_COOKIE['verify'] == md5($lp)) {
      $found = true;
      // prolong timeout
      if (TIMEOUT_CHECK_ACTIVITY) {
        setcookie("verify", md5($lp), $timeout, '/');
      }
      break;
    }
  }
  if (!$found) {
    showLoginPasswordProtect("");
  }

}

?>

thanks for your help,

zagga: yes i can move the folder above the public_html (root) folder so if i do this can only logged in users download the files?

ddymacek: the code you provided looks like to protect pages which i already have it is a folder which contains images and pdfs and word docs that i need to protect but without the use of htaccess as restrictions with hoster. i want it to run off my existing mysql database for the users login info?

thanks again

Try this:
create INDEX.PHP file in this folder and put redirection. It means that noone can open this folder and see the files inside it.

<?php
header("location:../");
?>

But, you have to add secure downloading. Because, if logged users sees the URL or something like this, he can tell someone URL, so, use something like this:

<?php
function files($id){
    //get real file name, and file name for downloading
    return $name."%".$name2;
}
if($_GET['id']){ //and if logged in
$id=$_GET['id'];
$fileName=files($id);
$fileName=explode("%",$fileName);
$fileRealName=$fileName[0];
$fileName2=$fileName[1];
$fileURL="files/".$fileName2;
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileRealName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
readfile($fileURL);
}
?>

When uploading file, change file name (eg. change "file.jpg" to "gh4s6s56fg.jpg"), and store real file name and old file name to database.

yes, you want to protect your 'directory' or 'folder'. correct? then make a page index.php and simply include this script in it. It would force someone to try and login if they hit that page. you can update the 'login information' to work off of your database instead of a hard coded list in the file. no one can ever view (without being logged in) the contents of that directory if this file is in the index.php page that would resolve when someone was trying to hit that particular directory. the question you asked was:
is there a script which will protect a directory and run off the mysql database username and password as opposed to just a standard htaccess file?
Yes, here it is, maybe you should test drive it, drop on your index page and see.
also why are you so concerned about files in a folder. there are many ways to not reveal what folder your files reside in when presenting them. ivan also had a good suggestion for you.

Member Avatar for Zagga

Howdy-hoooo mrhankey,

Any folder above your root directory is not web accessible. People can't just type a URL into a browser to reach the folder, or any files inside it.

Your code can access the files by using something like /home/yourusername/safefolder/protected_file.pdf. Only PHP (or other) files on the same server as the protected directory can access it.

Only include the code to access the files on members only pages (you already have this covered).

I want to protect my project folder with password with coding in php.
It happens in java bt i can't able to do in php so plz help

is it possible?

Did you even try the script pasted a few posts up?

yes sir bt I want to protect folder only.
as i click on my folder password is required is it possible through coding because i protect my folder by password in java with password by coding.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.