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
[WP7] DYNAMICALLY CHANGE STARTUP PAGE[WP7] DYNAMICALLY CHANGE STARTUP PAGE par KooKiz
Let's say that you want to allow the user to customize the startup page of your application. You can easily change the startup page by editing the 'NavigationPage' attribute in the manifest file. But the manifest cannot be modified once the applicatio...
Cliquez pour lire la suite de l'article par KooKiz SESSION SILVERLIGHT 5 3D : SLIDES ET DEMOSSESSION SILVERLIGHT 5 3D : SLIDES ET DEMOS par Groc
Durant les techdays, j'ai eu le plaisir d'animer une session sur Silverlight 5 et la 3D avec Simon Ferquel. Comme promis, voici nos slides et mes démos (celles avec le viper BSG) ici et là. Pour mémoire, les démos utilisent toutes le viper BSG...
Cliquez pour lire la suite de l'article par Groc [TECHDAYS 2012] SESSION WEBMATRIX 2 : LE COUTEAU SUISSE GRATUIT POUR VOS DéVELOPPEMENTS WEB - SLIDES[TECHDAYS 2012] SESSION WEBMATRIX 2 : LE COUTEAU SUISSE GRATUIT POUR VOS DéVELOPPEMENTS WEB - SLIDES par gpommier
Suite à la session que j'ai présenté sur WebMatrix 2, vous pouvez trouver les slides ici, ainsi que les démos en packages nuget : démos1 et démos2 J'en profite pour remercier chaleureusement tous ceux qui sont venus très nombreux à cette sess...
Cliquez pour lire la suite de l'article par gpommier [SHAREPOINT] LES SESSIONS TECHDAYS 2012.[SHAREPOINT] LES SESSIONS TECHDAYS 2012. par Patrick Guimonet
Voici donc pour ceux qui n'ont pas pu venir, ou ceux qui n'ont pas pu toutes les suivre la liste des sessions SharePoint aux TechDays 2012, que je mettrais à jour dès que les liens des vidéo seront disponibles. Ou ici : http...
Cliquez pour lire la suite de l'article par Patrick Guimonet TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3 par ROMELARD Fabrice
Speaker: Bernard Ourghanlian Cette session est comme chaque jour transmise en live par BrainSonic, et j'ai donc suivi cette troisième pleinière par ce moyen sur mon iPad . Elle est dédiée comme chaque année à la mise en perspective de l'é...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Forum
RE : SONDAGE..RE : SONDAGE.. par phpAnonyme
Cliquez pour lire la suite par phpAnonyme RE : SONDAGE..RE : SONDAGE.. par TychoBrahe
Cliquez pour lire la suite par TychoBrahe
Logiciels
Tribler (2012)TRIBLER (2012)Tribler est un client pair à pair (P2P/Peer-to-Peer) open source avec la capacité de regarder des... Cliquez pour télécharger Tribler OneSwarm (2012)ONESWARM (2012)Le peer-to-peer qui protège votre vie privée, c'est OneSwarm.
Ce logiciel de peer-to-peer crypté... Cliquez pour télécharger OneSwarm PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning
|