Accueil > > > GÉRER UN .HTPASSWD
GÉRER UN .HTPASSWD
Information sur la source
Description
Une mini source sans grande prétention: le but est de gérer un fichier .htpasswd de manière à ce que seuls les utilisateurs d'un site aient accès aux fichiers d'un répertoire. Je travaille en supposant qu'une connexion à une base de données existe et qu'une table users existe avec les champs suivants: * actif: si 1, l'utilisateur peut se loger * psw_htpasswd: champ qui contient le mot de passe pour le fichier .htpasswd * pseudo: 3 caractères qui désigne l'utilisateur
Source
- Voici un exemple d'utilisation:
- <?
- $htaccess = new htaccess( );
- $htaccess->set_folder( 'folder/' ); // dossier contenant le .htpasswd
-
- // si vous voulez ajouter un user à votre base de données:
- $psw_sha = $htaccess->non_salted_sha1( $psw ); // retourne le passord encodé que vous pouvez sauver
-
- // si vous voulez créer le fichier à partir de la base de données
- if( !$htaccess->create_htpasswd_from_bdd( ) )
- die( 'Erreur' );
- if( !$htaccess->write_files( ) )
- die( 'Erreur' );
-
- // si vous voulez ajouter un utilisateur
- if( !$htaccess->load_htpasswd( ) )
- die( 'Erreur' );
- $htaccess->add_user( $pseudo, $psw );
- if( !$htaccess->write_files( ) )
- die( 'Erreur' );
-
- // si vous voulez supprimer un user
- if( !$htaccess->load_htpasswd( ) )
- $htaccess->remove_user_from_htpasswd( $pseudo );
- if( !$htaccess->write_files( ) )
- die( 'Erreur' );
- ?>
-
-
- <?php
- /*
- htaccess.class.php
- Classe de gestion des fichiers .htaccess et .htpasswd
- Rafael GUGLIELMETTI
- Début: 28.02.2009, derniere modif 28.02.2009
- */
- class htaccess
- {
- public $error = NULL;
-
- private $htpasswd_content = NULL;
- private $htpasswd_rows = 0;
-
- private $folder = 'data/';
-
- /*
- load_htpasswd
- Lit le fichier des mots de passe
- Retour: bool
- */
-
- public function load_htpasswd( )
- {
- if( !file_exists( $this->folder . '.htpasswd' ) )
- {
- $this->htpasswd_rows = 0;
- $this->htpasswd_content = array( );
- return true;
- }
-
- if( ( $this->htpasswd_content = file( $this->folder . '.htpasswd' ) ) === false )
- {
- $this->error = 'LOAD_HTPASSWD';
- return false;
- }
-
- $this->htpasswd_content = array_map( 'rtrim', $this->htpasswd_content );
-
- $this->htpasswd_rows = count( $this->htpasswd_content );
-
- return true;
- }
-
- /*
- write_files
- Ecrit les fichiers
- Retour: bool
- */
- public function write_files( )
- {
- // ------------------------------------------------------------------
- // .htpasswd
- if( !$this->htpasswd_rows )
- {
- if( @file_put_contents( $this->folder . '.htpasswd', ' ' ) === false )
- return false;
- }
- else
- {
- if( @file_put_contents( $this->folder . '.htpasswd', implode( "\n", $this->htpasswd_content ) ) === false )
- return false;
- }
-
- // ------------------------------------------------------------------
- // .htaccess
- if( !file_exists( $this->folder . '.htaccess' ) )
- {
- $data = 'AuthName "Veuillez entrer votre visa et votre mot de passe"' . "\n";
- $data .= "AuthType Basic\n";
- $data .= 'AuthUserFile "' . realpath( $this->folder . '.htpasswd' ) . '"' . "\n";
- $data .= "Require valid-user\n";
-
- if( @file_put_contents( $this->folder . '/.htaccess', $data ) === false )
- return false;
- }
-
- return true;
- }
-
- /*
- add_user
- Ajoute un utilisateur
- */
- public function add_user( $visa, $psw )
- {
- if( isset( $this->htpasswd_content ) )
- $this->remove_user_from_htpasswd( $visa ); // suppression des anciennes occurences
- else
- $this->htpasswd_content[ ] = array( );
-
- $visa = strtoupper( $visa );
- $psw = $this->non_salted_sha1( $psw );
-
- $this->htpasswd_rows = count( $this->htpasswd_content );
-
- $this->htpasswd_content[ ] = $visa . ':' . $psw;
- $this->htpasswd_content[ ] = strtolower( $visa ) . ':' . $psw;
-
- $this->htpasswd_rows += 2;
- return $psw;
- }
-
- /*
- create_htpasswd_from_bdd
- Crée le fichier depuis la bdd
- Retour: bool
- */
- public function create_htpasswd_from_bdd( )
- {
- if( !( $ret = mysql_query( 'SELECT pseudo, psw_htpasswd FROM users WHERE actif=1' ) ) )
- {
- $this->error = 'GET_DATA';
- return false;
- }
-
- $this->htpasswd_content = array( );
- while( $row = mysql_fetch_row( $ret ) )
- {
- if( empty( $row[1] ) )
- continue ;
-
- $this->htpasswd_content[ ] = $row[0] . ':' . $row[1];
- $this->htpasswd_content[ ] = strtolower( $row[0] ) . ':' . $row[1];
- }
-
- $this->htpasswd_rows = count( $this->htpasswd_content );
-
- return true;
- }
-
- public function remove_user_from_htpasswd( $visa )
- {
- $find = $this->find_visa_in_array( $visa );
- $find_ = count( $find );
-
- $j = 0;
- for( $i = 0; $i < $find_; $i++ )
- {
- array_splice( $this->htpasswd_content, $find[$i] - $j, 1 );
- $j++;
- }
-
- $this->htpasswd_rows = count( $this->htpasswd_content );
- }
-
- /*
- find_visa_in_array
- Cherche les occurences d'un visa (insensible à la casse)
- */
- private function find_visa_in_array( $visa )
- {
- $find = array( );
- $visa = strtolower( $visa );
-
- for( $i = 0; $i < $this->htpasswd_rows; $i++ )
- {
- if( strlen( $this->htpasswd_content[$i] ) < 4 )
- continue ;
-
- if( strtolower( substr( $this->htpasswd_content[$i], 0, 3 ) ) == $visa )
- $find[ ] = $i;
- }
-
- return $find;
- }
-
- public function set_folder( $folder )
- {
- if( ( $len = strlen( $folder ) ) > 0 )
- {
- if( $folder[$len - 1] != '/' )
- $folder .= '/';
- }
-
- $this->folder = $folder;
- }
-
- // .htpasswd file functions
- // Copyright (C) 2004,2005 Jarno Elonen <elonen@iki.fi>
- //
- // Redistribution and use in source and binary forms, with or without modification,
- // are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright notice, this
- // list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright notice,
- // this list of conditions and the following disclaimer in the documentation
- // and/or other materials provided with the distribution.
- // * The name of the author may not be used to endorse or promote products derived
- // from this software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
- // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
- // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
- // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- //
- // Thanks to Jonas Wagner for SHA1 support.
-
- // Generate a SHA1 password hash *without* salt
- public function non_salted_sha1( $pass )
- {
- return "{SHA}" . base64_encode(pack("H*", sha1($pass)));
- }
- }
- ?>
Voici un exemple d'utilisation:
<?
$htaccess = new htaccess( );
$htaccess->set_folder( 'folder/' ); // dossier contenant le .htpasswd
// si vous voulez ajouter un user à votre base de données:
$psw_sha = $htaccess->non_salted_sha1( $psw ); // retourne le passord encodé que vous pouvez sauver
// si vous voulez créer le fichier à partir de la base de données
if( !$htaccess->create_htpasswd_from_bdd( ) )
die( 'Erreur' );
if( !$htaccess->write_files( ) )
die( 'Erreur' );
// si vous voulez ajouter un utilisateur
if( !$htaccess->load_htpasswd( ) )
die( 'Erreur' );
$htaccess->add_user( $pseudo, $psw );
if( !$htaccess->write_files( ) )
die( 'Erreur' );
// si vous voulez supprimer un user
if( !$htaccess->load_htpasswd( ) )
$htaccess->remove_user_from_htpasswd( $pseudo );
if( !$htaccess->write_files( ) )
die( 'Erreur' );
?>
<?php
/*
htaccess.class.php
Classe de gestion des fichiers .htaccess et .htpasswd
Rafael GUGLIELMETTI
Début: 28.02.2009, derniere modif 28.02.2009
*/
class htaccess
{
public $error = NULL;
private $htpasswd_content = NULL;
private $htpasswd_rows = 0;
private $folder = 'data/';
/*
load_htpasswd
Lit le fichier des mots de passe
Retour: bool
*/
public function load_htpasswd( )
{
if( !file_exists( $this->folder . '.htpasswd' ) )
{
$this->htpasswd_rows = 0;
$this->htpasswd_content = array( );
return true;
}
if( ( $this->htpasswd_content = file( $this->folder . '.htpasswd' ) ) === false )
{
$this->error = 'LOAD_HTPASSWD';
return false;
}
$this->htpasswd_content = array_map( 'rtrim', $this->htpasswd_content );
$this->htpasswd_rows = count( $this->htpasswd_content );
return true;
}
/*
write_files
Ecrit les fichiers
Retour: bool
*/
public function write_files( )
{
// ------------------------------------------------------------------
// .htpasswd
if( !$this->htpasswd_rows )
{
if( @file_put_contents( $this->folder . '.htpasswd', ' ' ) === false )
return false;
}
else
{
if( @file_put_contents( $this->folder . '.htpasswd', implode( "\n", $this->htpasswd_content ) ) === false )
return false;
}
// ------------------------------------------------------------------
// .htaccess
if( !file_exists( $this->folder . '.htaccess' ) )
{
$data = 'AuthName "Veuillez entrer votre visa et votre mot de passe"' . "\n";
$data .= "AuthType Basic\n";
$data .= 'AuthUserFile "' . realpath( $this->folder . '.htpasswd' ) . '"' . "\n";
$data .= "Require valid-user\n";
if( @file_put_contents( $this->folder . '/.htaccess', $data ) === false )
return false;
}
return true;
}
/*
add_user
Ajoute un utilisateur
*/
public function add_user( $visa, $psw )
{
if( isset( $this->htpasswd_content ) )
$this->remove_user_from_htpasswd( $visa ); // suppression des anciennes occurences
else
$this->htpasswd_content[ ] = array( );
$visa = strtoupper( $visa );
$psw = $this->non_salted_sha1( $psw );
$this->htpasswd_rows = count( $this->htpasswd_content );
$this->htpasswd_content[ ] = $visa . ':' . $psw;
$this->htpasswd_content[ ] = strtolower( $visa ) . ':' . $psw;
$this->htpasswd_rows += 2;
return $psw;
}
/*
create_htpasswd_from_bdd
Crée le fichier depuis la bdd
Retour: bool
*/
public function create_htpasswd_from_bdd( )
{
if( !( $ret = mysql_query( 'SELECT pseudo, psw_htpasswd FROM users WHERE actif=1' ) ) )
{
$this->error = 'GET_DATA';
return false;
}
$this->htpasswd_content = array( );
while( $row = mysql_fetch_row( $ret ) )
{
if( empty( $row[1] ) )
continue ;
$this->htpasswd_content[ ] = $row[0] . ':' . $row[1];
$this->htpasswd_content[ ] = strtolower( $row[0] ) . ':' . $row[1];
}
$this->htpasswd_rows = count( $this->htpasswd_content );
return true;
}
public function remove_user_from_htpasswd( $visa )
{
$find = $this->find_visa_in_array( $visa );
$find_ = count( $find );
$j = 0;
for( $i = 0; $i < $find_; $i++ )
{
array_splice( $this->htpasswd_content, $find[$i] - $j, 1 );
$j++;
}
$this->htpasswd_rows = count( $this->htpasswd_content );
}
/*
find_visa_in_array
Cherche les occurences d'un visa (insensible à la casse)
*/
private function find_visa_in_array( $visa )
{
$find = array( );
$visa = strtolower( $visa );
for( $i = 0; $i < $this->htpasswd_rows; $i++ )
{
if( strlen( $this->htpasswd_content[$i] ) < 4 )
continue ;
if( strtolower( substr( $this->htpasswd_content[$i], 0, 3 ) ) == $visa )
$find[ ] = $i;
}
return $find;
}
public function set_folder( $folder )
{
if( ( $len = strlen( $folder ) ) > 0 )
{
if( $folder[$len - 1] != '/' )
$folder .= '/';
}
$this->folder = $folder;
}
// .htpasswd file functions
// Copyright (C) 2004,2005 Jarno Elonen <elonen@iki.fi>
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Thanks to Jonas Wagner for SHA1 support.
// Generate a SHA1 password hash *without* salt
public function non_salted_sha1( $pass )
{
return "{SHA}" . base64_encode(pack("H*", sha1($pass)));
}
}
?>
Historique
- 01 mars 2009 11:44:27 :
- Mise en page
- 01 mars 2009 11:45:01 :
- Mise en page
- 01 mars 2009 11:51:51 :
- Petite correction
- 01 mars 2009 21:15:24 :
- Tit bug
Sources du même auteur
RÉCUPÉRER L'IP DU VISITEURRÉCUPÉRER L'IP DU VISITEUR Suite à un commentaire sur un source je vous propose, ce code, qui n'est pas de moi, et qui permet de récupérer l'ip du visiteur.
Ces deux fonction...
IMAGE ANTI-SPAMIMAGE ANTI-SPAMUn petit script tout simple qui crée une image anti-spam...
Deux versions (correspondant aux deux zones de la capture):
- une simple (mais plus fa...
MOTEUR DE RECHERCHE DANS BDD IIMOTEUR DE RECHERCHE DANS BDD II Voilà, une petite classe permettant de générer une requête de recherche pour une bdd.
J'ai déjà fait un code similaire ; la raison pour laquelle je n...
PRETTY DATEPRETTY DATE Pour commencer, l'idée de ce code et son implémentation ne sont pas de moi, il s'agit d'un code d'olid:
http://www.phpcs.com/codes/AFFICHER-DATE-HEUR...
FORMULAIRE (NEWS, LIVRE D'OR, ...)FORMULAIRE (NEWS, LIVRE D'OR, ...)Le zip contient le code pour faire un formulaire (pour un ajout de news, message dans livre d'or, etc).
Code HTML:
- formulaire en lui même
Cod...
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
apache 2 +.htaccerr [ par quarkiller ]
Hello !J'ai un problème de sécurité avecv mon serveur Apache 2.il interpréte bizzarement mes .htaccess. si je met AuthUserFile /Library/Apache2/htdoc
Protection avec .htaccess et .htpasswd [ par michel74380 ]
Bonjour,J'ai un répertoire avec des photos que j'ai protégé (le répertoir) avec .htaccess et .htpasswd.Jusque là, tout va bien. Pour accéder à mon rép
pb htaccess + htpasswd [ par girlbond ]
bonjour,j'ai créé un fichier htaccess qui contient ceci :AuthUserFile c:/program files/easyphp/www/gpi/ .htpasswdAuthGroupFile /dev/nullAuthName ByPas
MySql et .htaccess [ par GillesWebmaster ]
Bonjour, j'aimerais savoir si c'est possible de créer un script dans le fichier htpasswd qui se conencte à la base de donnée et qui per
Pb avec HTACCESS [ par anonymous38 ]
Bonjour tout le monde, j'ai un problème avec mon .htacess voici le code : AuthUserFile /vefhtdoc/toto/totoadmin/.htpasswd AuthGroupFile /dev/nul
comment faire de la sécurité?? [ par progrima ]
Bonsoir tout le mode. J'essaye de faire de l'authentification avec php et mysql. Selon certains articles sur le sujet, j'ai lu que pour sécuriser l'ac
Probleme htaccess htpasswd [ par youyou_2004 ]
Bonjour a tous, je fais un site en php et j'ai un probleme avec le htpasswd et le htaccess. Lorsque je rentre le nom d'utilisateur et le mot de passe
.htaccess & .htpasswd [ par gabs77 ]
je tente de comprendre comment fonctionne ses fichiers et voila ma configuration.htaccess=========AuthUserFile C:\Documents and Settings\bleach\Bureau
inclusion php, htaccess et sécurité [ par platon179 ]
Bonjour, Je suis actuellement en train de réaliser un site, et je m'emmêle les pinceaux avec les .htaccess etc... Je vous donne l'architecture du site
Generer un .htpasswd ?!? [ par Nik0p0le ]
Bonsoir,J'ai donc suivi la source de ce Monsieur : http://www.phpcs.com/codes/GERER-HTPASSWD_49384.aspxEt évidemment je ne comprends pas tout ,pour n
|
Derniers Blogs
TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2010 : PLAN DE MIGRATION VERS SHAREPOINT 2010TECHDAYS PARIS 2010 : PLAN DE MIGRATION VERS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Arnault Nouvel et Antoine Dongois Le processus à prendre : Apprendre (découvrir la plateforme) Préparer (documenter l'historique et choisir la méthode de MAJ) Test (Test de MAJ) Implémenter (Effectuer la MAJ) Valid...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2010 : LA PLEINIèRE DU SECOND JOURTECHDAYS PARIS 2010 : LA PLEINIèRE DU SECOND JOUR par ROMELARD Fabrice
Après un retour sur l'histoire des TechDays de Paris et le fait que ce soit le plus gros event MS au monde (du fait de sa gratuité), le président de MS France (Eric Boustoullier) a fait une présentation de la vision Microsoft pour les années à venir...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|