
Et voici... un blog de plus sur la toile!
A vrai dire, je n'avais pas pensé faire un blog au début, je voulais plutôt créer un site (un vrai de vrai, j'entend)
qui me permettrais de publier les scripts que j'ai réalisé au fil du temps (et que je réaliserai). Cependant,
après l'essai de quelques CMS (sites clés-en-main) et pas mal de déceptions (incompatibilités, code illisible et in-modifiable, ...), j'ai décidé de créer un blog.
Vous pourriez me faire remarquer, à juste titre d'ailleurs, que pour quelqu'un qui programme et bidouille, cela ne fait pas
très sérieux de piocher un site (ou un blog, en l'occurence) tout fait... La raison est que j'ai passé beaucoup de temps sur mon
"vrai" site (j'ai nommé Allpotes) et que je n'ai plus ni l'envie ni le temps de recommencer
quelque chose de zéro...
Alors, voili voilou, ce blog est né: La p'tite boîte à bouts de codes (et autres écrits). Je
vais tâcher d'y poster les scripts, bouts de codes, tutoriaux, etc, qui traînent dans les recoins de mon PC!
Bonne visite et n'hésitez pas à me faire part de vos remarques, critiques, lettres enflammées, ...
R@f
Un travail réalisé lors de notre cours de TP de mathématiques avec Dimitri Zaganidis.
Au menu:
Abstract:
Dans ce travail, nous présentons une introduction à la théorie
des catégories, notion unificatrice des structures algébriques et outil puissant des mathématiques
modernes. Nous exposons un développement ne nécessitant aucun
prérequis et conduisant à des lemmes de diagrammes utiles et ô
combien sympathiques.
Titre: Gérer un .htaccess et un .htpasswd
Date: Juillet 2009
Language: PHP
Description: 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
Exemple:
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' );
?>
Code principal
<?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)));
}
}
?>
Titre: Image anti spam V2
Date: Avril 2007
Language: PHP
Description: Ce code crée une image anti spam utile pour les livres d'or, ... L'image est plus difficile à lire que la version 1 (certains robots la contournaient trop facilement)

Utilisation:
Si le script est enregistré dans le fichier: anti_spam.php, on appèle l'image comme ceci:
<img src="anti_spam.php?name=livreor&strlen=4" alt="anti-flood" />
>> le contenu dans l'image sera dans $_SESSION['livreor']
>> 4 caractères
Si $spam représente l'entrée utilsateur, le test se fait comme ceci:
if( $_SESSION['livreor'] != strtoupper( $spam ) )
// erreur ici
Resources:
Si le script ne fonctionne pas, mettez cette police dans le répertoire du script.
Code de anti_spam.php
<?php
session_start();
// type de flood
$name = $_GET['name'];
// nb de caractères
$strlen = (int) $_GET['strlen'];
// taille de l'image ( width )
$width = $strlen * 23 + 20;
$height = 60;
// taille de chaque zone de couleur
$widthColor = $width / 4;
// création
$img = imagecreatetruecolor( $width, $height );
// antialising, c'est plus bô! :-)
imageantialias( $img, 1 );
// chaine
$string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$chaine = '';
for( $i = 0; $i < $strlen; $i++ )
$chaine .= $string[ mt_rand( 0, 35 ) ];
$_SESSION[ $name ] = $chaine;
// couleur de départ
$c1 = array( mt_rand( 200, 255), mt_rand( 200, 255), mt_rand( 200, 255) );
// couleur finale
$c2 = array( mt_rand( 70, 180), mt_rand( 70, 180), mt_rand( 70, 180) );
// pas pour chaque composante de couleur
$diffsColor = array( ( $c1[0] - $c2[0] ) / $widthColor, ( $c1[1] - $c2[1] ) / $widthColor, ( $c1[2] - $c2[2] ) / $widthColor );
$start = 0;
$end = $widthColor;
for( $j = 0; $j < 4; $j++ ) // boucle pour chacune des 4 zones
{
$r = $j % 2 == 0 ? $c1[0] : $c2[0]; // composante r de départ
$v = $j % 2 == 0 ? $c1[1] : $c2[1]; // idem v
$b = $j % 2 == 0 ? $c1[2] : $c2[2]; // idem b
// création des lignes
for( $i = $start; $i < $end; $i++ )
{
if( $j % 2 == 0 )
{
$r -= $diffsColor[0];
$v -= $diffsColor[1];
$b -= $diffsColor[2];
}
else
{
$r += $diffsColor[0];
$v += $diffsColor[1];
$b += $diffsColor[2];
}
$color = imagecolorallocate( $img, $r, $v, $b );
imageline( $img, $i, 0, $i, $height, $color );
}
$start += $widthColor;
$end += $widthColor;
}
$colorsChar = array( ); // on va mémoriser les couleurs des caractères
// caractères
for( $i = 0; $i < $strlen; $i++ )
{
$colorsChar[$i] = imagecolorallocate( $img, mt_rand( 0, 120 ), mt_rand( 0, 120 ), mt_rand( 0, 120 ) );
imagettftext( $img, mt_rand( 20, 25 ), mt_rand( -35, 35 ), 10 + $i * 23, 35, $colorsChar[$i], 'comic.ttf', $chaine[ $i ] );
}
// quelques lignes qui embêtent
for( $i = 0; $i < 10; $i++ )
{
imageline( $img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $colorsChar[mt_rand( 0, $strlen - 1 )] );
}
$noir = imagecolorallocate( $img, 0, 0, 0 );
// bordure
imageline( $img, 0, 0, $width, 0, $noir );
imageline( $img, 0, 0, 0, $height, $noir );
imageline( $img, $width - 1, 0, $width - 1, $height, $noir );
// header: image
header("Content-type: image/png");
imagepng( $img );
imagedestroy( $img );
?>
Titre: Image anti spam
Date: Août 2006
Language: PHP
Description: Ce code crée une image anti spam utile pour les livres d'or, ...

Utilisation:
Si le script est enregistré dans le fichier: anti_spam.php, on appèle l'image comme ceci:
>> le contenu dans l'image sera dans $_SESSION['livreor']
>> 4 caractères
Si $spam représente l'entrée utilsateur, le test se fait comme ceci:
if( $_SESSION['livreor'] != strtoupper( $spam ) )
// erreur ici
Resources:
Si le script ne fonctionne pas, mettez cette police dans le répertoire du script.
Code de anti_spam.php
<?php
session_start();
// type de flood
$name = $_GET['name'];
// nb de caractères
$strlen = (int) $_GET['strlen'];
// taille de l'image ( width )
$width = $strlen * 30 + 20;
$height = 60;
// création
$img = imagecreatetruecolor( $width, $height );
// antialising, c'est plus bô! :-)
imageantialias( $img, 1 );
// chaine
$string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$chaine = '';
for( $i = 0; $i < $strlen; $i++ )
$chaine .= $string[ mt_rand( 0, 35 ) ];
$_SESSION[ $name ] = $chaine;
// couleur de départ
$c1 = array( mt_rand( 200, 255), mt_rand( 200, 255), mt_rand( 200, 255) );
// couleur finale
$c2 = array( mt_rand( 150, 200), mt_rand( 150, 200), mt_rand( 150, 200) );
$colors = array( imagecolorallocate( $img, 70, 130, 255 ) , imagecolorallocate( $img, 255, 237, 175 ), imagecolorallocate( $img, 166, 250, 186 ), imagecolorallocate( $img, 253, 188, 251 ), imagecolorallocate( $img, 255, 255, 255 ) );
// création de l'image
for( $i = 0; $i < $width; $i++ )
{
$r = $c1[0] + $i * ( $c2[0] - $c1[0] ) / $width;
$v = $c1[1] + $i * ( $c2[1] - $c1[1] ) / $width;
$b = $c1[2] + $i * ( $c2[2] - $c1[2] ) / $width;
$color = imagecolorallocate( $img, $r, $v, $b );
imageline( $img, $i, 0, $i, $height, $color );
}
// caractères
for( $i = 0; $i < $strlen; $i++ )
{
$col = imagecolorallocate( $img, mt_rand( 0, 120 ), mt_rand( 0, 120 ), mt_rand( 0, 120 ) );
imagettftext( $img, mt_rand( 20, 25 ), mt_rand( -30, 30 ), 10 + $i * 30, 35, $col, 'comic.ttf', $chaine[ $i ] );
}
// quelques lignes qui embêtent
for( $i = 0; $i < 8; $i++ )
{
imageline( $img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $colors[mt_rand( 0, 4 )] );
}
$noir = imagecolorallocate( $img, 0, 0, 0 );
// bordure
imageline( $img, 0, 0, $width, 0, $noir );
imageline( $img, 0, 0, 0, $height, $noir );
imageline( $img, $width - 1, 0, $width - 1, $height, $noir );
// header: image
header("Content-type: image/png");
imagepng( $img );
imagedestroy( $img );
?>
Titre: Récupérer l'ip du visiteur
Date: -
Language: PHP
Description: Ce code permet de récupérer l'ip du visiteur. Ce code n'est pas de moi, il appartient à PhpMyAdmin.
<?php
function PMA_getIp( )
{
global $REMOTE_ADDR;
global $HTTP_X_FORWARDED_FOR, $HTTP_X_FORWARDED, $HTTP_FORWARDED_FOR, $HTTP_FORWARDED;
global $HTTP_VIA, $HTTP_X_COMING_FROM, $HTTP_COMING_FROM;
// Get some server/environment variables values
if( empty( $REMOTE_ADDR ) && PMA_getenv( 'REMOTE_ADDR' ) )
$REMOTE_ADDR = PMA_getenv( 'REMOTE_ADDR' );
if ( empty( $HTTP_X_FORWARDED_FOR ) && PMA_getenv( 'HTTP_X_FORWARDED_FOR' ) )
$HTTP_X_FORWARDED_FOR = PMA_getenv( 'HTTP_X_FORWARDED_FOR' );
if( empty( $HTTP_X_FORWARDED ) && PMA_getenv( 'HTTP_X_FORWARDED' ) )
$HTTP_X_FORWARDED = PMA_getenv( 'HTTP_X_FORWARDED' );
if ( empty( $HTTP_FORWARDED_FOR ) && PMA_getenv( 'HTTP_FORWARDED_FOR' ) )
$HTTP_FORWARDED_FOR = PMA_getenv( 'HTTP_FORWARDED_FOR' );
if ( empty( $HTTP_FORWARDED ) && PMA_getenv( 'HTTP_FORWARDED' ) )
$HTTP_FORWARDED = PMA_getenv( 'HTTP_FORWARDED' );
if ( empty( $HTTP_VIA ) && PMA_getenv( 'HTTP_VIA' ) )
$HTTP_VIA = PMA_getenv( 'HTTP_VIA' );
if ( empty( $HTTP_X_COMING_FROM ) && PMA_getenv( 'HTTP_X_COMING_FROM' ) )
$HTTP_X_COMING_FROM = PMA_getenv( 'HTTP_X_COMING_FROM' );
if ( empty( $HTTP_COMING_FROM ) && PMA_getenv( 'HTTP_COMING_FROM' ) )
$HTTP_COMING_FROM = PMA_getenv( 'HTTP_COMING_FROM' );
// Gets the default ip sent by the user
if ( !empty( $REMOTE_ADDR ) )
$direct_ip = $REMOTE_ADDR;
// Gets the proxy ip sent by the user
$proxy_ip = '';
if ( !empty( $HTTP_X_FORWARDED_FOR ) )
$proxy_ip = $HTTP_X_FORWARDED_FOR;
elseif ( !empty( $HTTP_X_FORWARDED ) )
$proxy_ip = $HTTP_X_FORWARDED;
elseif ( !empty( $HTTP_FORWARDED_FOR ) )
$proxy_ip = $HTTP_FORWARDED_FOR;
elseif ( !empty( $HTTP_FORWARDED ) )
$proxy_ip = $HTTP_FORWARDED;
elseif ( !empty( $HTTP_VIA ) )
$proxy_ip = $HTTP_VIA;
elseif ( !empty( $HTTP_X_COMING_FROM ) )
$proxy_ip = $HTTP_X_COMING_FROM;
elseif ( !empty( $HTTP_COMING_FROM ) )
$proxy_ip = $HTTP_COMING_FROM;
// end if... elseif...
// Returns the true IP if it has been found, else FALSE
if ( empty( $proxy_ip ) )
return $direct_ip; // True IP without proxy
else
{
$is_ip = preg_match( '|^( [0-9]{1,3}\. ){3,3}[0-9]{1,3}|', $proxy_ip, $regs );
if ( $is_ip && ( count( $regs ) > 0 ) )
return $regs[0]; // True IP behind a proxy
else
{
// Can't define IP: there is a proxy but we don't have
// information about the true IP
return FALSE;
}
} // end if... else...
} // end of the 'PMA_getIp( )' function
/**
* trys to find the value for the given environment vriable name
*
* searchs in $_SERVER, $_ENV than trys getenv( ) and apache_getenv( )
* in this order
*
* @param string $var_name variable name
* @return string value of $var or empty string
*/
function PMA_getenv( $var_name )
{
if ( isset( $_SERVER[$var_name] ) )
return $_SERVER[$var_name];
elseif ( isset( $_ENV[$var_name] ) )
return $_ENV[$var_name];
elseif ( getenv( $var_name ) )
return getenv( $var_name );
elseif ( function_exists( 'apache_getenv' ) && apache_getenv( $var_name, true ) )
return apache_getenv( $var_name, true );
return '';
}
?>