begin process at 2010 02 09 19:19:10
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Sécurité & Cryptage

 > GÉRER UN .HTPASSWD

GÉRER UN .HTPASSWD


 Information sur la source

Note :
10 / 10 - par 1 personne
10,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Sécurité & Cryptage Classé sous :sécurité, htpasswd, htaccess, crypter Niveau :Débutant Date de création :01/03/2009 Date de mise à jour :01/03/2009 21:15:24 Vu :3 475

Auteur : coockiesch

Ecrire un message privé
Site perso
Commentaire sur cette source (2)
Ajouter un commentaire et/ou une note

 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 VISITEUR
Source avec Zip Source avec une capture IMAGE ANTI-SPAM
MOTEUR DE RECHERCHE DANS BDD II
PRETTY DATE
Source avec Zip Source avec une capture FORMULAIRE (NEWS, LIVRE D'OR, ...)

 Sources de la même categorie

ALGORITHME DE CÉSAR SUR LA TABLE ASCII par Nementon
Source avec une capture CODEC D'OBFUSCATION DE LIEN HTML (PHP5) par masternico
Source avec Zip SERSESSIONS > CLASS PHP5 POUR GERER LES SESSIONS SIMPLEMENT par Astalavista
Source avec Zip PROTECTION CONTRE LES FAILLES CSRF : CROSS SITE REQUEST FORG... par aKheNathOn
Source avec Zip SECURISATION D'UNE ZONE par liptibilly

 Sources en rapport avec celle ci

SECURITÉ PROTECTION AUTOMATIQUE CONTRE MAGICQUOTE ET REGISTE... par TheWeasel47
ENLEVER DES BALISES HTML DANS UNE TEXTAREA par keket
GÉNÉRATEUR DE CLÉ par jynolen
CONTROLE D'ACCÈS AVEC WWW-AUTHENTICATE: par monsieurjean
Source avec Zip SCRIPT QUI GÉNÈRE UN FICHIER .HTPASSWD ET UN FICHIER .HTACCE... par The_Template

Commentaires et avis

Commentaire de LaurentKOogar le 02/03/2009 11:19:11

"pseudo: 3 caractères qui désigne l'utilisateur"

ton chti nom c'est Raf je crois (3 lettres)... sinon Merci pour ce code, ca manquait sur le Net tout comme toi d'ailleurs, j'espere que c'est un vrai come back :)

Commentaire de Nik0p0le le 12/07/2009 23:51:20 10/10

Merci pour cette source, même si je comprends pas encore
tout c'est sympa à toi de l'avoir poster .

 Ajouter un commentaire


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&#233;er un script dans le fichier htpasswd qui se conencte &#224; la base de donn&#233;e et qui per Pb avec HTACCESS [ par anonymous38 ] Bonjour tout le monde, j'ai un probl&#232;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


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,827 sec (4)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales