Results for php : 102

1 - fonction PHP - servir un fichier avec headers corrects
function serveFile($path){

	if (is_file($path)){
		$mime=mime_content_type($path);
		header('Content-type: '.$mime.'; charset=utf-8');
		header('Content-Transfer-Encoding: binary');
		header('Content-Disposition: filename="'.tools::basename($path).'"');
		header('Content-Length: '.filesize($path));
		readfile($path);
		exit;
	}
        header("HTTP/1.1 404 Not Found");
        exit('404 - Not Found (╯°□°)╯︵ ┻━┻');

}
			
2 - folder2array()
function folder2array($path=''){
		//$path=empty($path)?'./':$path;
		$array=[];
		$current_dir=glob($path.'/*');
		if ($current_dir[0]==$path) unset($current_dir[0]);
		foreach ($current_dir as $key => $item) {
			if (is_file($item)){
				$array[]=$item;
			}else{
				$array[]=folder2array($item);
			}
		}
		return $array;
	}
			
4 - ordonner un tableau en fonction de la longueur des chaines qui le composent
function order($a,$b){
    return strlen($b)-strlen($a);
}
usort($mots,'order');

			
6 - trier des fichiers par date (ascendant)
$files=glob('*');

usort(
        $files,
        function($file1, $file2) {
        return filemtime($file1) <=> filemtime($file2);
    }
);

// pour descendant:
$files=array_reverse($files);
			
7 - aujourdhui() - la date du jour en français
function aujourdhui()
    {
        $jour=@date("D");
        $njour=@date("j");
        $nmois=@date("n");
        $an=@date("Y");
        $ja="Mon Tue Wen Thu Fri Sat Sun ";
        $jf="Lundi Mardi Mercredi Jeudi Vendredi Samedi Dimanche ";
        $tjours=explode(" ",$jf);
        $mf="Janvier Février Mars Avril Mai Juin Juillet Août Septembre Octobre Novembre Décembre ";
        $tmois=explode(" ",$mf);

        $nj=strpos($ja,$jour)/4;

        $jour=$tjours[$nj];
        $mois=$tmois[$nmois-1];
        $z=$jour." ".$njour." ".$mois." ".$an;
        return $z;
    }
			
8 - Obtenir l'adresse de l'article en cours dans PluXml
$url_article=$plxShow->plxMotor->urlRewrite('index.php?article'.$plxShow->plxMotor->plxRecord_arts->f('numero').'/'.$plxShow->plxMotor->plxRecord_arts->f('url'))
			
9 - Chemin vers un plugin dans pluXML
$plxMotor=plxMotor::getInstance();
$plugin=$plxMotor->plxPlugins->aPlugins['nom_du_plugin'];
$plugin->methode();
			
10 - encoder-decoder une chaine - compatible URL pour GET
function base64url_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
} 
			
13 - Liste de couleurs HTML sous forme de tableau PHP
$colors=[ 
	"transparent",    
		"Maroon",
		"DarkRed",
		"FireBrick",
		"Red",
		"Salmon",
		"Tomato",
		"Coral",
		"OrangeRed",
		"Chocolate",
		"SandyBrown",
		"DarkOrange",
		"Orange",
		"DarkGoldenrod",
		"Goldenrod",
		"Gold",
		"Olive",
		"Yellow",
		"YellowGreen",
		"GreenYellow",
		"Chartreuse",
		"LawnGreen",
		"Green",
		"Lime",
		"LimeGreen",
		"SpringGreen",
		"MediumSpringGreen",
		"Turquoise",
		"LightSeaGreen",
		"MediumTurquoise",
		"Teal",
		"DarkCyan",
		"Aqua",
		"Cyan",
		"DarkTurquoise",
		"DeepSkyBlue",
		"DodgerBlue",
		"RoyalBlue",
		"Navy",
		"DarkBlue",
		"MediumBlue",
		"Blue",
		"BlueViolet",
		"DarkOrchid",
		"DarkViolet",
		"Purple",
		"DarkMagenta",
		"Fuchsia",
		"Magenta",
		"MediumVioletRed",
		"DeepPink",
		"HotPink",
		"Crimson",
		"Brown",
		"IndianRed",
		"RosyBrown",
		"LightCoral",
		"Snow",
		"MistyRose",
		"DarkSalmon",
		"LightSalmon",
		"Sienna",
		"SeaShell",
		"SaddleBrown",
		"Peachpuff",
		"Peru",
		"Linen",
		"Bisque",
		"Burlywood",
		"Tan",
		"AntiqueWhite",
		"NavajoWhite",
		"BlanchedAlmond",
		"PapayaWhip",
		"Moccasin",
		"Wheat",
		"Oldlace",
		"FloralWhite",
		"Cornsilk",
		"Khaki",
		"LemonChiffon",
		"PaleGoldenrod",
		"DarkKhaki",
		"Beige",
		"LightGoldenrodYellow",
		"LightYellow",
		"Ivory",
		"OliveDrab",
		"DarkOliveGreen",
		"DarkSeaGreen",
		"DarkGreen",
		"ForestGreen",
		"LightGreen",
		"PaleGreen",
		"Honeydew",
		"SeaGreen",
		"MediumSeaGreen",
		"Mintcream",
		"MediumAquamarine",
		"Aquamarine",
		"DarkSlateGray",
		"PaleTurquoise",
		"LightCyan",
		"Azure",
		"CadetBlue",
		"PowderBlue",
		"LightBlue",
		"SkyBlue",
		"LightskyBlue",
		"SteelBlue",
		"AliceBlue",
		"SlateGray",
		"LightSlateGray",
		"LightsteelBlue",
		"CornflowerBlue",
		"Lavender",
		"GhostWhite",
		"MidnightBlue",
		"SlateBlue",
		"DarkSlateBlue",
		"MediumSlateBlue",
		"MediumPurple",
		"Indigo",
		"MediumOrchid",
		"Plum",
		"Violet",
		"Thistle",
		"Orchid",
		"LavenderBlush",
		"PaleVioletRed",
		"Pink",
		"LightPink",
		"Black",
		"DimGray",
		"Gray",
		"DarkGray",
		"Silver",
		"LightGrey",
		"Gainsboro",
		"WhiteSmoke",
		"White"
	];
			
15 - makeFavIcon - créer un favicon avec un logo et un fond coloré


function makeFavIcon($background_color){
  # Si on a changé la coupeur dans color.php
  if (filemtime('favicon.png')!=filemtime('colors.php')){
    # on charge le logo
    $logo=imagecreatefrompng ('img/logo.png');
    # ça c'est pour la transparence
    imageAlphaBlending($logo, true);
    imageSaveAlpha($logo, true);

    # on crée l'image de fond
    $fav=imagecreatetruecolor(140,140);
    imageAlphaBlending($fav, true);
    imageSaveAlpha($fav, true);

    # on extrait la couleur (passée en #fff ou #ffffff)
    preg_match('/#?([a-fA-F0-9]{1,2})([a-fA-F0-9]{1,2})([a-fA-F0-9]{1,2})/',$background_color,$color);
    if (strlen($color[1])<2){
      $color[1]=$color[1].$color[1];
      $color[2]=$color[2].$color[2];
      $color[3]=$color[3].$color[3];
    }
    $color=array_map("hexdec",$color);
    $color = ImageColorAllocate ($fav,$color[1],$color[2],$color[3]);
    
    # on crée le fond dans la couleur
    imagefilledrectangle ($fav,0,0,140,140,$color);
    imagecopy($fav,$logo,0,0,0,0,140,140);

    # on sauve l'image
    imagepng($fav, 'favicon.png');
     
    # on libère la mémoire
    imagedestroy($fav);

    # on change le filemtime du fichier de couleurs
    touch('colors.php');
  }
}

			
16 - array_search - recherche dans un tableau multidimensionnel
in (PHP 5 >= 5.5.0) you don't have to write your own function to search through a multi dimensional array

ex : 

$userdb=Array
(
    (0) => Array
        (
            (uid) => '100',
            (name) => 'Sandra Shush',
            (url) => 'urlof100'
        ),

    (1) => Array
        (
            (uid) => '5465',
            (name) => 'Stefanie Mcmohn',
            (pic_square) => 'urlof100'
        ),

    (2) => Array
        (
            (uid) => '40489',
            (name) => 'Michael',
            (pic_square) => 'urlof40489'
        )
);

simply u can use this

$key = array_search(40489, array_column($userdb, 'uid'));
			
17 - astuce sécurité PHP - Le Hollandais Volant
# en début de script
if (basename($_SERVER['SCRIPT_NAME']) === 'index.php' and strpos(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), 'index.php') === FALSE ) {
	$var_request_URI = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH).'index.php';
} else {
	$var_request_URI = $_SERVER['REQUEST_URI'];
}
if (parse_url($var_request_URI, PHP_URL_PATH) !== $_SERVER['SCRIPT_NAME']) {
	header('Location: '.$_SERVER['SCRIPT_NAME']);
}


			
18 - aff v2.0
	function aff($var,$stop=true){
		$dat=debug_backtrace();$origin='<table>';
		echo '<div style="background-color:rgba(0,0,0,0.8);color:red;padding:5px">Arret ligne <em><strong style="color:white;font-weight:bold">'.$dat[0]['line'].'</strong></em> dans le fichier <em style="color:white;font-weight:bold">'.$dat[0]['file'].'</em></div>';
		echo '<pre style="background-color:rgba(0,0,0,0.8);color:#fff;padding:10px"><code>';var_dump($var);echo '</code></pre>';
		foreach (array_reverse($dat) as $data){
			$dir=dirname($data['file']).'/';
			$fil=basename($data['file']);
			$origin.='<tr><td style="width:50%"><em style="color:#888">'.$dir.'</em></td><td style="max-width:10%"><em style="color:white;font-weight:bold">'.$fil.'</em></td><td style="max-width:10%"><em style="color:yellow;font-weight:bold">'.$data['function'].'()</em></td><td style="max-width:10%"> <em style="color:lightblue;font-weight:bold">'.$data['line'].'</em> </td></tr>';
		}
		$origin.='</table>';
		echo '<div style="background-color:rgba(0,0,0,0.8);color:#aaa;padding:10px">'.$origin.'</div>';
		if ($stop){exit();}
	}
			
19 - auto_css minimal
<?php
/**
 * On-the-fly CSS Compression
 * Copyright (c) 2009 and onwards, Manas Tungare. (changes by bronco)
 * Creative Commons Attribution, Share-Alike.
 *
 * In order to minimize the number and size of HTTP requests for CSS content,
 * this script combines multiple CSS files into a single file and compresses
 * it on-the-fly.
 *
 * To use this in your HTML, link to it in the usual way:
 * <link rel="stylesheet" type="text/css" media="screen, print, projection" href="/css/compressed.css.php" />
 */



/*
* this version detects css files and allow very basic replacements (bronco@warriordudimanche.net)
*/
# replacement rules: "String to replace" => "Replacement"
$replace=array(
  '#basic_color_neutral'=>'#405bff',
  '#basic_color_dark'=>'#2039ee',
  '#basic_color_light'=>'#617dff',
  '#hover_color'=>'',
);


# function
if (!function_exists('_glob')){
  function _glob($path,$pattern='') {
    # glob function fallback by Cyril MAGUIRE (thx bro' ;-)
    if($path=='/'){
      $path='';
    }
      $liste =  array();
      $pattern=str_replace('*','',$pattern);
      if ($handle = opendir($path)) {
          while (false !== ($file = readdir($handle))) {
            if(stripos($file, $pattern)!==false || $pattern=='' && $file!='.' && $file!='..' && $file!='.htaccess') {
                  $liste[] = $path.$file;
              }
          }
          closedir($handle);
      }
    natcasesort($liste);
      return $liste;
     
  }

}
$cssFiles = _glob('./','css');
/**
 * Ideally, you wouldn't need to change any code beyond this point.
 */
$buffer = "";
foreach ($cssFiles as $cssFile) {
  $buffer .= file_get_contents($cssFile);
}
$buffer=str_replace(array_keys($replace),array_values($replace),$buffer);

// Remove unnecessary characters
$buffer = preg_replace("|/\*[^*]*\*+([^/][^*]*\*+)*/|", "", $buffer);
$buffer = preg_replace("/[\s]*([\:\{\}\;\,])[\s]*/", "$1", $buffer);

// Remove whitespace
$buffer = str_replace(array("\r\n", "\r", "\n"), '', $buffer);

// Enable GZip encoding.
ob_start("ob_gzhandler");

// Enable caching
header('Cache-Control: public');

// Expire in one day
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');

// Set the correct MIME type, because Apache won't set it for us
header("Content-type: text/css");

// Write everything out
echo($buffer);
?>

			
20 - safe_redirect: rediriger une page sans erreur headers already sent
function safe_redirect($url=none){
	if (!$url){return false;}
	if (!headers_sent()){header('location: '.$url);}
	else{echo '<script>document.location.href="'.$url.'";</script>';}
	exit;
}
			
21 - multi_curl_content - récupérer les contenus de plusieurs url en une fois
// url=array(url1,url2,url3)
// return: array(url1=>content1,url2=>content2 etc)
function multi_curl_contents($urls){
	// from http://lehollandaisvolant.net/?d=2014/05/20/19/21/36-php-faire-plusieurs-requetes-http-simultanees-avec-curl
	$multihandler = curl_multi_init();
	$handlers = $result = array();
	foreach ($urls as $url) {
		$handlers[$url] = curl_init($url);
		curl_setopt($handlers[$url], CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($handlers[$url], CURLOPT_FOLLOWLOCATION, TRUE);
		curl_setopt($handlers[$url], CURLOPT_COOKIESESSION, TRUE);
		curl_setopt($handlers[$url], CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt($handlers[$url], CURLOPT_TIMEOUT, 30);
                curl_setopt($handlers[$i], CURLOPT_TIMEOUT, 30);
		curl_multi_add_handle($multihandler, $handlers[$url]);
                curl_setopt($handlers[$i], CURLOPT_ENCODING, "gzip");
	}
	do {
		curl_multi_exec($multihandler, $pendingConnex);		
		usleep(10000); // 10 ms
	} while ($pendingConnex > 0);
	foreach ($urls as $url) {$result[$url] = curl_multi_getcontent($handlers[$url]);}
	return $result;
}
			
22 - récupérer le titre d'une page web
$url = "http://example.com/";

$html_source = file_get_contents($url);
$dom_tree = new DOMDocument();
$dom_tree->loadHTML($html_source);
$titles = $dom_tree->getElementsByTagName('title');
$title = trim($titles->item(0)->nodeValue);

return $title;

// pour éviter les erreurs de pages mal foutues
libxml_use_internal_errors(true);
// dom parsing
libxml_clear_errors();

			
23 - ssave-sload: secured data saving
# Secured save/load variable data (inspired by Oros)
function ssave($file=null,$content=''){
	if (!$file){return false;}
	file_put_contents($file.'.php', '<?php /* '.base64_encode(gzdeflate(serialize($content))).' */ ?>');
}
function sload($file=null){
	if (!$file || !is_file($file)){return false;}
	return unserialize(gzinflate(base64_decode(substr(file_get_contents($file),9,-strlen(6)))));
}
			
24 - glob - fallback
	if (function_exists('glob')){
		function _glob($path,$pattern='*'){return glob($path.$pattern);}
	}else{
		function _glob($path,$pattern='') {
		    # glob function fallback by Cyril MAGUIRE (thx bro' ;-)
		    $liste =  array();
		    $pattern=str_replace('*','',$pattern);
		    if ($handle = opendir($path)) {
		        while (false !== ($file = readdir($handle))) {
		        	if(stripos($file, $pattern)!==false || $pattern=='') {
		                $liste[] = $path.$file;
		            }
		        }
		        closedir($handle);
		    }
		    if (!empty($liste)) {
		        return $liste;
		    } else {
		        return array();
		    }
		}
	}
			
25 - Scanner un dossier et sous dossier dans un array
	function tree($dir='.',$files=false){
		if (!isset($dossiers[0]) || $dossiers[0]!=$dir){$dossiers[0]=$dir;}
		if (!is_dir($dir)&&$files){ return array($dir); }
		elseif (!is_dir($dir)&&!$files){return array();}
		$list=glob($dir.'/*');		

		# retrait des fichiers si demandé
		if (!$files){
			foreach($list as $key=>$val){ if (is_file($val)){unset($list[$key]);} }
		}
		# scanne chaque sous dossier récursivement
		foreach ($list as $dossier) {
			// pour un tableau reproduisant la structure de l'arborescence
			// remplacer la ligne ci-dessous par 
			// $dossiers[]=tree($dossier); 
			$dossiers=array_merge($dossiers,tree($dossier,$files));
		}
		return $dossiers;
	}
			
27 - FORMULAIRE DE MODIFICATION DES DROITS CHMOD DES FICHIERS ET DOSSIERS
<?php
/*
FORMULAIRE DE MODIFICATION DES DROITS CHMOD DES FICHIERS ET DOSSIERS
Enregistrez ce fichier dans votre répertoire hébergement web, ouvrez-le 
avec votre navigateur et suivez les instructions.
Un rapport d'erreur est fourni.
*/

// initialisation des variables
$dosPerm = "0";
$ficPerm = "0";
$retval = "0"; // nombre d'erreurs CHMOD

 // Chemin du dossier a traiter
    $chem = preg_replace("/[^_A-Za-z0-9-\.%\/]/i",'', $_POST["chemin"]);    // chemin de fichier absolu (avec nettoyage contre piratage)
    $chem = preg_replace("/\.\.\//",'', $chem);    // on interdit la commande ../
    define('ABSPATH', dirname(__FILE__));
    $chem = ABSPATH.$chem;    // chemin de fichier absolu de votre compte du genre /home/loginftp/www/ ou /home/loginftp/public_html/ etc.

//Droits des dossiers
    $d1 = preg_replace("/[^057]/",'', $_POST["dir1"]);
    $d2 = preg_replace("/[^057]/",'', $_POST["dir2"]);
    $d3 = preg_replace("/[^057]/",'', $_POST["dir3"]);
    $dosPerm = "0".$d1.$d2.$d3;
    $dosPerm = octdec($dosPerm);
//droits des fichiers
    $f1 = preg_replace("/[^046]/i",'', $_POST["fic1"]);
    $f2 = preg_replace("/[^046]/i",'', $_POST["fic2"]);
    $f3 = preg_replace("/[^046]/i",'', $_POST["fic3"]);
    $ficPerm = "0".$f1.$f2.$f3;
    $ficPerm = octdec($ficPerm);

// Formulaire html pour changer les droits
    print "<html><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />";
    print "<body><h3>Changer les droits d'acc&egrave;s CHMOD aux dossiers et fichiers <br />dans votre h&eacute;bergement.</h3>";
    print "<table><tr><td>";
    print "<form method=\"post\">";
    print "<tr><td>Droits des dossiers: </td>";
    print "<td><select name=\"dir1\"><option value=\"0\">0</option><option value=\"5\">5</option><option value=\"7\" selected>7</option></select><select name=\"dir2\"><option value=\"0\">0</option><option value=\"5\" selected>5</option><option value=\"7\">7</option></select><select name=\"dir3\"><option value=\"0\">0</option><option value=\"5\" selected>5</option><option value=\"7\">7</option></select></td></tr>";
    print "<tr><td>Droits des fichiers: </td>";
    print "<td><select name=\"fic1\"><option value=\"0\">0</option><option value=\"4\">4</option><option value=\"6\" selected>6</option></select><select name=\"fic2\"><option value=\"0\">0</option><option value=\"4\" selected>4</option><option value=\"6\">6</option></select><select name=\"fic3\"><option value=\"0\">0</option><option value=\"4\" selected>4</option><option value=\"6\">6</option></select></td></tr>";
    print "<tr><td>R&eacute;pertoire &agrave; contr&ocirc;ler: </td>";
    print "<td>".ABSPATH." <input type=\"text\" name=\"chemin\" maxlength=\"80\" size=\"30\" value=\"/\" ></td></tr>";
    print "<tr><td> </td><td><input type=\"submit\" value=\" Changer les CHMOD des Dossiers et Fichiers \">";
    print "</form>";
    print "</td></tr></table>";

if ( ($dosPerm||$ficPerm) > 0 ){

    function rChmod($chem,$dosPerm,$ficPerm) {
        echo "<p><b>Journal:</b></p>\r\n";

        $d = new RecursiveDirectoryIterator($chem); 
        $d ->setFlags(RecursiveDirectoryIterator::SKIP_DOTS); 
        foreach (new RecursiveIteratorIterator($d, 1) as $path) {
            $chmodret = false;
            $chmodresultat = "";
            if ( $path->isDir() ) {
            $chmodret = chmod( $path, $dosPerm ); }
            else {
            if ( is_file( $path )  ) {
            $chmodret = chmod( $path, $ficPerm ); }
            }
            if ($chmodret) {$chmodresultat = "OK"; }
            else {
                $chmodresultat = "ERREUR";
                ++$retval;
                }
            echo $chmodresultat . " " . $path . "<br />\r\n";
        }
    return $retval;
}
    $nbfailed = rChmod($chem,$dosPerm,$ficPerm);
    echo "<p><b>";
    if ($nbfailed > 0) {
        echo $nbfailed . " erreur(s) CHMOD. Voyez le journal ci-dessus.";
        }
    else echo "Pas d'erreur apparente. Vérifiez par vous-même.</b></p>\r\n";
}
?>
			
29 - savejson-loadjson - sauver/lire des données en une ligne
<?php
function savejson($file,$datas){return file_put_contents($file,'<?php/*'.serialize($datas).'*/?>');}
function loadjson($file){return unserialize(str_replace(array('<?php/*','*/?>'),'',file_get_contents($file)));}


?>
			
33 - strip_almost_all_tags
function strip_almost_all_tags($chaine){
	// ajouter le strip attributes
	// à la barbare
	$secure='#on(click|dblclick|blur|change|dragdrop|focus|keydown|keyup|keypress|mouseover|mouseout|load|unload|keydown)=#i';
	$keep=array('<img ','<a ', '<em', '<br>','<br/>','</a', '</em', '<br />','<p ', '</p','<div ', '</div','<span ', '</span', '<li', '</li', '<ul', '</ul');
	$temp_repl=array('[img ','[a ','[em','[br]','[br/]','[/a','[/em','[br /]','[p ','[/p','[div ','[/div','[span ','[/span','[li','[/li','[ul','[/ul');
	$chaine=str_ireplace($keep,$temp_repl,$chaine);
	$chaine=strip_tags($chaine);
	$chaine=preg_replace($secure, 'on$1&#61;', $chaine);
	return str_ireplace($temp_repl,$keep,$chaine);
}
			
34 - load/save serialized var
	function load($filename){
		if (empty($filename)||!is_file($filename)){return false;}
		return unserialize(file_get_contents($filename));
	}	
	function save($filename,$data){
		if (empty($filename))){return false;}	
		file_put_contents($filename,serialize($data));
	}
			
35 - globDir - glob alternative
/**
 * Fonction listant le contenu d'un dossier et qui ne retourne que les fichiers dont les extensions sont autorisées
 *
 * @param $path string le chemin absolu vers le dossier à traiter
 * @return $liste array un tableau contenant le chemin vers les fichiers dont l'extension est valide
 *
 * @author Cyril MAGUIRE
 */
function globDir($path) {
    $liste =  array();
    $extensions = array('jpg','jpeg','gif','png','bmp','JPG','JPEG','GIF','PNG','BMP');
    if ($handle = opendir($path)) {
        while (false !== ($file = readdir($handle))) {
            if(in_array(substr($file, strrpos($file, '.')+1), $extensions)) {
                $liste[] = $path.$file;
            }
        }
        closedir($handle);
    }
    if (!empty($liste)) {
        return $liste;
    } else {
        return false;
    }
}
			
37 - Générer un breadcrumb à partir d'une URL
<?php 
// this function generates a simple breadcrumb 
if ( ! function_exists('breadcrumb')) { 
    function breadcrumb($data = array()) 
    { 
        $breadcrumb = '<ul class="breadcrumb">'."\n"; 
        if(isset($data)) { 
            foreach ($data as $link) { 
                if((isset($link[2])) AND ($link[2] === TRUE)) { 
                    $breadcrumb .= '<li class="active"><span>'.$link[1].'</span></li>'."\n"; 
                } else { 
                    $breadcrumb .= '<li><a href="'.$link[0].'">'.$link[1].'</a></li>'."\n"; 
                } 
            } 
        } 
        $breadcrumb .= '</ul>'."\n"; 

        return $breadcrumb; 
    } 
} 

// Below is an example of how to generate the breadcrumb 
$breadcrumb = array( 
    array('http://localhost/', 'Home'), 
    array('', 'Register', TRUE), 
    ); 

echo breadcrumb($breadcrumb); 

/* 
|---------------------------------------------------------------- 
| This will echo 
| 
| <ul class="breadcrumb"> 
|   <li><a href="http://localhost/">Home</a></li> 
|   <li class="active"><span>Register</span></li> 
| </ul> 
|---------------------------------------------------------------- 
| 
| You can use the following css 
| [credit to : iTemplates | http://dinakit.itemplat.es/] 
| 
| .breadcrumb { background-color: #FEFEFE; list-style: none; margin: 0 0 20px; padding: 8px 15px; font-size: 12px; } 
| .breadcrumb > li { display: inline-block; *display: inline; *zoom: 1; } 
| .breadcrumb > li:after { content: "\2022"; color: #DDDDDD; padding: 0 5px 0 10px; } 
| .breadcrumb > li:last-child:after { content: none; } 
| .breadcrumb > li > a:link, 
| .breadcrumb > li > a:visited { text-decoration: none; } 
| .breadcrumb > li > a:hover, 
| .breadcrumb > li > a:active, 
| .breadcrumb > li > a:focus { text-decoration: underline; } 
| .breadcrumb > .active > span, 
| .breadcrumb > .active > a { color: #999999; text-decoration: none; cursor: default; } 
*/
			
38 - get_video_infos - infos sur une video youtube
function file_curl_contents($url,$pretend=true){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Charset: UTF-8'));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,  FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        if (!ini_get("safe_mode") && !ini_get('open_basedir') ) {curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);}
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        if ($pretend){curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/29.0');}
    
        curl_setopt($ch, CURLOPT_REFERER, '');
        $data = curl_exec($ch);
        $response_headers = curl_getinfo($ch);

        // Google seems to be sending ISO encoded page + htmlentities, why??
        if($response_headers['content_type'] == 'text/html; charset=ISO-8859-1') $data = html_entity_decode(iconv('ISO-8859-1', 'UTF-8//TRANSLIT', $data)); 
        
        # $data = curl_exec($ch);

        curl_close($ch);

        return $data;
    }


function get_video_infos($url=null){
	// returns an array with all the youtube video's informations (available qualities/urls/format...)
	if (!empty($url)){
		if ($contenu=file_curl_contents($url)){
			preg_match_all('#"url_encoded_fmt_stream_map": "(.*?)"#', $contenu, $resultats);
			preg_match_all('#<title>(.*?)</title>#', $contenu, $title);
			$c=0;
			$p=array('title'=>$title[1][0]);
			$params=explode('\u0026',$resultats[1][0]); 
			foreach ($params as $param){
				$temp=explode('=',$param);
				if (isset($p[$c][$temp[0]])){$c++;}
				$p[$c][$temp[0]]=urldecode($temp[1]);
			}
			return $p;
		}else{return false;}
	}else{return false;}

}


echo '<pre>';print_r(get_video_infos('http://www.youtube.com/watch?v=oHg5SJYRHA0'));
			
39 - file_curl_contents + referrer custom
	function file_curl_contents($url,$pretend=true){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Charset: UTF-8'));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,  FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		if (!ini_get("safe_mode") && !ini_get('open_basedir') ) {curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);}
		curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
		if ($pretend){curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0');}
    
		curl_setopt($ch, CURLOPT_REFERER, random_referer());// notez le referer "custom"

		$data = curl_exec($ch);
		$response_headers = curl_getinfo($ch);

		// Google seems to be sending ISO encoded page + htmlentities, why??
		if($response_headers['content_type'] == 'text/html; charset=ISO-8859-1') $data = html_entity_decode(iconv('ISO-8859-1', 'UTF-8//TRANSLIT', $data)); 
		
		# $data = curl_exec($ch);

		curl_close($ch);

		return $data;
	}


	function Random_referer(){
		return array_rand(array(
			'http://oudanstoncul.com.free.fr/‎',
			'http://googlearretedenousfliquer.fr/‎',
			'http://stopspyingme.fr/‎',
			'http://spyyourassfuckinggoogle.fr/‎',
			'http://dontfuckinglookatme.fr/‎',
			'http://matemonculgoogle.fr/‎',
			'http://auxarmescitoyens.fr/‎',
			'http://jetlametsavecdugravier.con/‎',
			'http://lesdeuxpiedsdanstagueule.fr/‎',
			'http://moncoudedanstabouche.con/‎',
			'http://monpieddanston.uk/‎',
			'http://bienfaitpourvosgueul.es/‎',
			'http://pandanstesdents.fr/‎',
			'http://tupuessouslesbras.fr/‎',
			'http://mangetescrottesdenez.fr/‎',
			'http://jtepourristesstats.fr/‎',
			'http://ontecompissevigoureusement.com/‎',
			'http://lepoingleveetlemajeuraussi.com/‎',
		));
	}
			
40 - pluxml-admin-comments.php - ajouter ip au nom du posteur de commentaires
echo '<td>'.plxUtils::strCut($plxAdmin->plxRecord_coms->f('author'),30).' / '.$plxAdmin->plxRecord_coms->f('ip').'&nbsp;</td>';

			
41 - clean - nettoyer une variable
function clean($value) {

       // If magic quotes not turned on add slashes.
       if(!get_magic_quotes_gpc())

       // Adds the slashes.
       { $value = addslashes($value); }

       // Strip any tags from the value.
       $value = strip_tags($value);

       // Return the value out of the function.
       return $value;

}
			
42 - afficher variables, fonctions et constantes déclarées
//afficher toutes les variables déclarées
exit('<pre>' . htmlspecialchars(print_r(get_defined_vars(), true)) . '</pre>');
//afficher toutes les constantes déclarées
exit('<pre>' . htmlspecialchars(print_r(get_defined_constants(), true)) . '</pre>');
//afficher toutes les fonctions déclarées
exit('<pre>' . htmlspecialchars(print_r(get_defined_functions(), true)) . '</pre>');
			
43 - Parsedown - version fonction
<?php
#
#
# Parsedown
# http://parsedown.org
#
# (c) Emanuil Rusev
# http://erusev.com
#

#This version is not the original: it's a class to function conversion by Bronco (http:www.warriordudimanche.net)
#Thanks a lot to Emanuil Rusev for this script ! It saved me lots of time ! ;-)

	global $escape_sequence_map;
	function parse($text)
	{
		# removes UTF-8 BOM and marker characters
		$text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);

		# removes \r characters
		$text = str_replace("\r\n", "\n", $text);
		$text = str_replace("\r", "\n", $text);

		# replaces tabs with spaces
		$text = str_replace("\t", '    ', $text);

		# encodes escape sequences
		if (strpos($text, '\\') !== FALSE)
		{
			$escape_sequences = array('\\\\', '\`', '\*', '\_', '\{', '\}', '\[', '\]', '\(', '\)', '\>', '\#', '\+', '\-', '\.', '\!');
			foreach ($escape_sequences as $index => $escape_sequence)
			{
				if (strpos($text, $escape_sequence) !== FALSE)
				{
					$code = "\x1A".'\\'.$index.';';
					$text = str_replace($escape_sequence, $code, $text);
					$escape_sequence_map[$code] = $escape_sequence;
				}
			}
		}

		# ~

		$text = preg_replace('/\n\s*\n/', "\n\n", $text);
		$text = trim($text, "\n");
		$lines = explode("\n", $text);
		$text = parse_block_elements($lines);

		# decodes escape sequences
		if (!empty($escape_sequence_map)){
			foreach ($escape_sequence_map as $code => $escape_sequence)
			{
				$text = str_replace($code, $escape_sequence[1], $text);
			}
		}

		$text = rtrim($text, "\n");
		return $text;
	}

	function parse_block_elements(array $lines, $context = '')
	{
		$elements = array();
		$element = array('type' => '',);

		foreach ($lines as $line)
		{
			# markup (open)
			if ($element['type'] === 'markup' and ! isset($element['closed']))
			{
				if (preg_match('{<'.$element['subtype'].'>$}', $line)) # opening tag
				{
					$element['depth']++;
				}

				if (preg_match('{</'.$element['subtype'].'>$}', $line)) # closing tag
				{
					$element['depth'] > 0
						? $element['depth']--
						: $element['closed'] = true;
				}
				$element['text'] .= "\n".$line;
				continue;
			}

			# *

			if ($line === '')
			{
				$element['interrupted'] = true;
				continue;
			}

			# blockquote (existing)
			if ($element['type'] === 'blockquote' and ! isset($element['interrupted']))
			{
				$line = preg_replace('/^[ ]*>[ ]?/', '', $line);
				$element['lines'] []= $line;
				continue;
			}

			# list (existing)
			if ($element['type'] === 'li')
			{
				if (preg_match('/^([ ]{0,3})(\d+[.]|[*+-])[ ](.*)/', $line, $matches))
				{
					if ($element['indentation'] !== $matches[1])
					{
						$element['lines'] []= $line;
					}
					else
					{
						unset($element['last']);
						$elements []= $element;
						$element = array(
							'type' => 'li',
							'indentation' => $matches[1],
							'last' => true,
							'lines' => array(
								preg_replace('/^[ ]{0,4}/', '', $matches[3]),
							),
						);
					}
					continue;
				}

				if (isset($element['interrupted']))
				{
					if ($line[0] === ' ')
					{
						$element['lines'] []= '';
						$line = preg_replace('/^[ ]{0,4}/', '', $line);
						$element['lines'] []= $line;
						continue;
					}
				}
				else
				{
					$line = preg_replace('/^[ ]{0,4}/', '', $line);
					$element['lines'] []= $line;
					continue;
				}
			}

			# paragraph
			if ($line[0] >= 'a' or $line[0] >= 'A' and $line[0] <= 'Z')
			{
				goto paragraph;
			}

			# code block
			if ($line[0] === ' ' and preg_match('/^[ ]{4}(.*)/', $line, $matches))
			{
				if (trim($line) === ''){continue;}
				if ($element['type'] === 'code')
				{
					if (isset($element['interrupted']))
					{
						$element['text'] .= "\n";
						unset ($element['interrupted']);
					}
					$element['text'] .= "\n".$matches[1];
				}
				else
				{
					$elements []= $element;
					$element = array(
						'type' => 'code',
						'text' => $matches[1],
					);
				}
				continue;
			}

			# setext heading (---)

			if ($line[0] === '-' and $element['type'] === 'p' and ! isset($element['interrupted']) and preg_match('/^[-]+[ ]*$/', $line))
			{
				$element['type'] = 'h.';
				$element['level'] = 2;
				continue;
			}

			# atx heading (#)

			if ($line[0] === '#' and preg_match('/^(#{1,6})[ ]*(.+?)[ ]*#*$/', $line, $matches))
			{
				$elements []= $element;
				$level = strlen($matches[1]);
				$element = array(
					'type' => 'h.',
					'text' => $matches[2],
					'level' => $level,
				);
				continue;
			}

			# setext heading (===)
			if ($line[0] === '=' and $element['type'] === 'p' and ! isset($element['interrupted']) and preg_match('/^[=]+[ ]*$/', $line))
			{
				$element['type'] = 'h.';
				$element['level'] = 1;
				continue;
			}

			$deindented_line = $line[0] !== ' ' ? $line : ltrim($line);
			if ($deindented_line === ''){continue;}

			# reference
			if ($deindented_line[0] === '[' and preg_match('/^\[(.+?)\]:[ ]*([^ ]+)/', $deindented_line, $matches))
			{
				$label = strtolower($matches[1]);
				$url = trim($matches[2], '<>');
				$reference_map[$label] = $url;
				continue;
			}

			# blockquote
			if ($deindented_line[0] === '>' and preg_match('/^>[ ]?(.*)/', $deindented_line, $matches))
			{
				if ($element['type'] === 'blockquote')
				{
					if (isset($element['interrupted']))
					{
						$element['lines'] []= '';
						unset($element['interrupted']);
					}
					$element['lines'] []= $matches[1];
				}
				else
				{
					$elements []= $element;
					$element = array(
						'type' => 'blockquote',
						'lines' => array(
							$matches[1],
						),
					);
				}
				continue;
			}

			# markup

			if ($deindented_line[0] === '<')
			{
				# self-closing tag
				if (preg_match('{^<.+?/>$}', $deindented_line))
				{
					$elements []= $element;
					$element = array(
						'type' => '',
						'text' => $deindented_line,
					);
					continue;
				}

				# opening tag
				if (preg_match('{^<(\w+)(?:[ ].*?)?>}', $deindented_line, $matches))
				{
					$elements []= $element;
					$element = array(
						'type' => 'markup',
						'subtype' => strtolower($matches[1]),
						'text' => $deindented_line,
						'depth' => 0,
					);
					preg_match('{</'.$matches[1].'>\s*$}', $deindented_line) and $element['closed'] = true;
					continue;
				}
			}

			# horizontal rule
			if (preg_match('/^([-*_])([ ]{0,2}\1){2,}[ ]*$/', $deindented_line))
			{
				$elements []= $element;
				$element = array('type' => 'hr',);
				continue;
			}

			# list item
			if (preg_match('/^([ ]*)(\d+[.]|[*+-])[ ](.*)/', $line, $matches))
			{
				$elements []= $element;
				$element = array(
					'type' => 'li',
					'ordered' => isset($matches[2][1]),
					'indentation' => $matches[1],
					'last' => true,
					'lines' => array(
						preg_replace('/^[ ]{0,4}/', '', $matches[3]),
					),
				);
				continue;
			}

			paragraph:
			if ($element['type'] === 'p')
			{
				if (isset($element['interrupted']))
				{
					$elements []= $element;
					$element['text'] = $line;
					unset($element['interrupted']);
				}
				else {$element['text'] .= "\n".$line;}
			}
			else
			{
				$elements []= $element;
				$element = array(
					'type' => 'p',
					'text' => $line,
				);
			}
		}

		$elements []= $element;
		array_shift($elements);

		
		$markup = '';
		foreach ($elements as $index => $element)
		{
			switch ($element['type'])
			{
				case 'p':
					$text = parse_span_elements($element['text']);
					$text = preg_replace('/[ ]{2}\n/', '<br />'."\n", $text);
					if ($context === 'li' and $index === 0)
					{
						if (isset($element['interrupted']))	{	$markup .= "\n".'<p>'.$text.'</p>'."\n";}
						else {$markup .= $text;}
					}
					else{$markup .= '<p>'.$text.'</p>'."\n";}
					break;

				case 'blockquote':
					$text =parse_block_elements($element['lines']);
					$markup .= '<blockquote>'."\n".$text.'</blockquote>'."\n";
					break;

				case 'code':
					$text = htmlentities($element['text'], ENT_NOQUOTES);
					strpos($text, "\x1A\\") !== FALSE and $text = strtr($text, $escape_sequence_map);
					$markup .= '<pre><code>'.$text.'</code></pre>'."\n";
					break;

				case 'h.':
					$text = parse_span_elements($element['text']);
					$markup .= '<h'.$element['level'].'>'.$text.'</h'.$element['level'].'>'."\n";
					break;

				case 'hr':
					$markup .= '<hr />'."\n";
					break;

				case 'li':
					if (isset($element['ordered'])) # first
					{
						$list_type = $element['ordered'] ? 'ol' : 'ul';
						$markup .= '<'.$list_type.'>'."\n";
					}
					if (isset($element['interrupted']) and ! isset($element['last']))
					{
						$element['lines'] []= '';
					}
					$text = parse_block_elements($element['lines'], 'li');
					$markup .= '<li>'.$text.'</li>'."\n";
					isset($element['last']) and $markup .= '</'.$list_type.'>'."\n";
					break;

				default:
					$markup .= $element['text']."\n";
			}
		}
		return $markup;
	}

	function parse_span_elements($text)
	{
		$map = array();
		$index = 0;

		# code span
		if (strpos($text, '`') !== FALSE and preg_match_all('/`(.+?)`/', $text, $matches, PREG_SET_ORDER))
		{
			foreach ($matches as $matches)
			{
				$element_text = $matches[1];
				$element_text = htmlentities($element_text, ENT_NOQUOTES);

				# decodes escape sequences
				$escape_sequence_map
					and strpos($element_text, "\x1A") !== FALSE
					and $element_text = strtr($element_text, $escape_sequence_map);

				# composes element
				$element = '<code>'.$element_text.'</code>';

				# encodes element
				$code = "\x1A".'$'.$index;
				$text = str_replace($matches[0], $code, $text);
				$map[$code] = $element;
				$index ++;
			}
		}

		# inline link or image

		if (strpos($text, '](') !== FALSE and preg_match_all('/(!?)(\[((?:[^\[\]]|(?2))*)\])\((.*?)\)/', $text, $matches, PREG_SET_ORDER)) # inline
		{
			foreach ($matches as $matches)
			{
				$url = $matches[4];
				strpos($url, '&') !== FALSE and $url = preg_replace('/&(?!#?\w+;)/', '&amp;', $url);
				if ($matches[1]) # image
				{
					$element = '<img alt="'.$matches[3].'" src="'.$url.'">';
				}
				else
				{
					$element_text =parse_span_elements($matches[3]);
					$element = '<a href="'.$url.'">'.$element_text.'</a>';
				}

	
				$code = "\x1A".'$'.$index;
				$text = str_replace($matches[0], $code, $text);
				$map[$code] = $element;
				$index ++;
			}
		}

		# reference link or image
		if (strpos($text, '[') !== FALSE and preg_match_all('/(!?)\[(.+?)\](?:\n?[ ]?\[(.*?)\])?/ms', $text, $matches, PREG_SET_ORDER))
		{
			foreach ($matches as $matches)
			{
				$link_definition = isset($matches[3]) && $matches[3]
					? $matches[3]
					: $matches[2]; # implicit

				$link_definition = strtolower($link_definition);
				if (isset($reference_map[$link_definition]))
				{
					$url = $reference_map[$link_definition];
					strpos($url, '&') !== FALSE and $url = preg_replace('/&(?!#?\w+;)/', '&amp;', $url);
					if ($matches[1]) # image
					{
						$element = '<img alt="'.$matches[2].'" src="'.$url.'">';
					}
					else # anchor
					{
						$element_text = parse_span_elements($matches[2]);
						$element = '<a href="'.$url.'">'.$element_text.'</a>';
					}

					
					$code = "\x1A".'$'.$index;
					$text = str_replace($matches[0], $code, $text);
					$map[$code] = $element;
					$index ++;
				}
			}
		}

		# automatic link

		if (strpos($text, '<') !== FALSE and preg_match_all('/<((https?|ftp|dict):[^\^\s]+?)>/i', $text, $matches, PREG_SET_ORDER))
		{
			foreach ($matches as $matches)
			{
				$url = $matches[1];
				strpos($url, '&') !== FALSE and $url = preg_replace('/&(?!#?\w+;)/', '&amp;', $url);
				$element = '<a href=":href">:text</a>';
				$element = str_replace(':text', $url, $element);
				$element = str_replace(':href', $url, $element);
				
				$code = "\x1A".'$'.$index;
				$text = str_replace($matches[0], $code, $text);
				$map[$code] = $element;
				$index ++;
			}
		}

		
		strpos($text, '&') !== FALSE and $text = preg_replace('/&(?!#?\w+;)/', '&amp;', $text);
		strpos($text, '<') !== FALSE and $text = preg_replace('/<(?!\/?\w.*?>)/', '&lt;', $text);

		if (strpos($text, '_') !== FALSE)
		{
			$text = preg_replace('/__(?=\S)(.+?)(?<=\S)__(?!_)/s', '<strong>$1</strong>', $text);
			$text = preg_replace('/_(?=\S)(.+?)(?<=\S)_/s', '<em>$1</em>', $text);
		}

		if (strpos($text, '*') !== FALSE)
		{
			$text = preg_replace('/\*\*(?=\S)(.+?)(?<=\S)\*\*(?!\*)/s', '<strong>$1</strong>', $text);
			$text = preg_replace('/\*(?=\S)(.+?)(?<=\S)\*/s', '<em>$1</em>', $text);
		}

		$text = strtr($text, $map);
		return $text;
	}
?>
			
44 - Formulaires: noms pour tableaux multidimensionnels
    echo '<input type="hidden" name="devoirs['.$key.'][titre]" value="'.$devoir['titre'].'"/>'.$r;
    echo '<input type="hidden" name="devoirs['.$key.'][date]" value="'.$devoir['date'].'"/>'.$r;
    echo '<input type="hidden" name="devoirs['.$key.'][note_globale]" value="'.$devoir['note_globale'].'"/>'.$r;
			
46 - BBCode Parser function
<?php

/* Simple PHP BBCode Parser function */

//BBCode Parser function

function showBBcodes($text) {

// BBcode array
$find = array(
'~\[b\](.*?)\[/b\]~s',
'~\[i\](.*?)\[/i\]~s',
'~\[u\](.*?)\[/u\]~s',
'~\[quote\](.*?)\[/quote\]~s',
'~\[size=(.*?)\](.*?)\[/size\]~s',
'~\[color=(.*?)\](.*?)\[/color\]~s',
'~\[url\]((?:ftp|https?)://.*?)\[/url\]~s',
'~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s'
);

// HTML tags to replace BBcode
$replace = array(
'<b>$1</b>',
'<i>$1</i>',
'<span style="text-decoration:underline;">$1</span>',
'<pre>$1</'.'pre>',
'<span style="font-size:$1px;">$2</span>',
'<span style="color:$1;">$2</span>',
'<a href="$1">$1</a>',
'<img src="$1" alt="" />'
);

// Replacing the BBcodes with corresponding HTML tags
return preg_replace($find,$replace,$text);
}

// How to use the above function:

$bbtext = "This is [b]bold[/b] and this is [u]underlined[/u] and this is in [i]italics[/i] with a [color=red] red color[/color]";
$htmltext = showBBcodes($bbtext);
echo $htmltext;

?>


			
47 - Lister les articles des catégories actives
<ul>
    <?php ob_start();
	$plxShow->catList('',"
	<li><a id=\"toggler-#cat_id\" href=\"#cat_url\" onclick=\"toggleDiv('cat-#cat_id','toggler-#cat_id','+ #cat_name','- #cat_name');return false;\" title=\"#cat_name\">+ #cat_name</a> (#art_nb)
		<ul id=\"cat-#cat_id\" class=\"hide\">
			[#cat_id]
		</ul>   
	</li>");
	$list = ob_get_clean();
	preg_match_all('!\[([a-zA-Z0-9-_])*\]!',$list,$match);
	$art = array();
	foreach ($match[1] as $key => $value) {
		ob_start();
		$plxShow->lastArtList('<li><a href="#art_url">#art_title</a> (#art_nbcoms)</li>', 5, $value,'');
		$art[$key] = ob_get_clean();
	}
	foreach ($match[0] as $key => $value) {
		$list = str_replace(array('&#039;',$value),array('\'',$art[$key]),$list);
	}
	              echo $list;				
?>

</ul>


			
50 - search2feed
<?php
# search2feed 
# @author: bronco@warriordudimanche.net / warriordudimanche.net
# @version 0.1
# @license  free and opensource
# @use: search2feed.php?q=your+query+here


function Random_referer(){
		return array_rand(array(
			'http://oudanstoncul.com.free.fr/‎',
			'http://googlearretedenousfliquer.fr/‎',
			'http://stopspyingme.fr/‎',
			'http://spyyourassfuckinggoogle.fr/‎',
			'http://dontfuckinglookatme.fr/‎',
			'http://matemonculgoogle.fr/‎',
			'http://auxarmescitoyens.fr/‎',
			'http://jetlametsavecdugravier.con/‎',
			'http://lesdeuxpiedsdanstagueule.fr/‎',
			'http://moncoudedanstabouche.con/‎',
			'http://monpieddanston.uk/‎',
			'http://bienfaitpourvosgueul.es/‎',
			'http://pandanstesdents.fr/‎',
			'http://tupuessouslesbras.fr/‎',
			'http://mangetescrottesdenez.fr/‎',
			'http://jtepourristesstats.fr/‎',
			'http://ontecompissevigoureusement.com/‎',
			'http://lepoingleveetlemajeuraussi.com/‎',
		));
	}


	function return_UTF8($var){		
		$utf8=str_replace("\xef\xbb\xbf\xA0", '',utf8_encode($var));// SANS BOM !!!!

		if (strpos($var,"\xA0")){return $utf8;}
		if (strpos($utf8,'Ã')){return $var;}else {return $utf8;}
	
	}

	function file_curl_contents($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Charset: UTF-8'));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,  FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		if (!ini_get("safe_mode") && !ini_get('open_basedir') ) {curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);}
		curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
		curl_setopt($ch, CURLOPT_REFERER, random_referer());// notez le referer "custom"

		$data = curl_exec($ch);
		$response_headers = curl_getinfo($ch);

		// Google seems to be sending ISO encoded page + htmlentities, why??
		if($response_headers['content_type'] == 'text/html; charset=ISO-8859-1') $data = html_entity_decode(iconv('ISO-8859-1', 'UTF-8//TRANSLIT', $data)); 
		
		# $data = curl_exec($ch);

		curl_close($ch);

		return return_utf8($data);
	}
	function parse_query($query,$title='Search2feed',$nb, $link='http://warriordudimanche.net',$lang='fr',$safesearch='&safe=off'){
		$REGEX_WEB='#(?<=<h3 class="r"><a href="/url\?q=)([^&]+).*?>(.*?)</a>.*?(?<=<span class="st">)(.*?)(?=</span>)#';
		$REGEX_PAGES='#&start=([0-9]+)|&start=([0-9]+)#';
		$lang=strip_tags($lang);
		$URL='https://www.google.com/search?hl='.$lang.$safesearch.'&id=hp&q=';

		$page=file_curl_contents($URL.str_replace(' ','+',urlencode($query)).'&num='.$nb);

		if (!$page){return false;}
		preg_match_all($REGEX_WEB, $page, $r);
		preg_match_all($REGEX_PAGES,$page,$p);
		$p=count($p[2]);

		$content=array();
		foreach ($r[1] as $key=>$val){
			$content[$key]['description']=strip_tags($r[3][$key]);
			$content[$key]['link']=strip_tags($r[1][$key]);
			$content[$key]['title']=strip_tags($r[2][$key]);
			$content[$key]['guid']=strip_tags($r[1][$key]).'#1';
			$content[$key]['pubDate']=@date('r');

		}

		$rss=array(
			'infos'=>array(
				'type'=>'rss',
				'description'=>strip_tags($query),
				'title'=>$title,
				'link'=>$link,
				
			),
			'items'=>$content
		);

		return $rss;
		
	}
function array2feed($array=null){
	if (!$array){return false;}
	
	if (empty($array['infos']['type'])){$array['infos']['type']='rss';}else{$array['infos']['type']=strtolower($array['infos']['type']);}
	if (empty($array['infos']['description'])){$array['infos']['description']='';}
	$r="\n";$t="\t";
	$tpl=array('rss'=>array(),'atom'=>array());
	$tpl['rss']['header']='<?xml version="1.0" encoding="utf-8" ?>'.$r.'<rss version="2.0"  xmlns:content="http://purl.org/rss/1.0/modules/content/">'.$r.$t.'<channel>'.$r;
	$tpl['atom']['header']='<feed xmlns="http://www.w3.org/2005/Atom">'.$r;
	$tpl['rss']['footer']=$t.'</channel></rss>'.$r;
	$tpl['atom']['footer']='</feed>'.$r;
	$tpl['rss']['content-type']='Content-Type: application/rss+xml';
	$tpl['atom']['content-type']='Content-Type: application/atom+xml;charset=utf-8';

	header($tpl[$array['infos']['type']]['content-type']);
	$feed=$tpl[$array['infos']['type']]['header'];
		//create the feed's info content
		foreach($array['infos'] as $key=>$value){
			if ($array['infos']['type']=='atom'){ // ATOM
				if ($key=='link'){$feed.=$t.$t.'<link href="'.$value.'" rel="self" type="application/atom+xml"/>'.$r;}
				elseif ($key=='author'){$feed.=$t.$t.'<author><name>'.$value.'</name></author>'.$r;}
				elseif ($key=='licence'){$feed.=$t.$t.'<'.$key.' href="'.$value.'" rel="license"/>'.$r;} // in atom feed, licence is the link to the licence type
				elseif ($key!='version'&&$key!='type'){$feed.=$t.$t.'<'.$key.'>'.$value.'</'.$key.'>'.$r;}
			}else{ // RSS
				if ($key!='version'&&$key!='type'){$feed.=$t.$t.'<'.$key.'>'.$value.'</'.$key.'>'.$r;}
			}
		}

		//then the items content
		foreach ($array['items'] as $item){
			if ($array['infos']['type']=='atom'){ $feed.=$t.$t.$t.'<entry>'.$r;}else{$feed.=$t.$t.$t.'<item>'.$r;}
				foreach($item as $key=>$value){
					if ($array['infos']['type']=='atom'){ // ATOM
						if ($key=='link'){$feed.=$t.$t.$t.$t.'<link href="'.$value.'" rel="alternate" type="text/html"/>'.$r;}
						elseif ($key=='content'){$feed.=$t.$t.$t.$t.'<content type="text">'.htmlspecialchars($value).'</content>'.$r;}
						else{$feed.=$t.$t.$t.$t.'<'.$key.'>'.$value.'</'.$key.'>'.$r;}
					}else{ // RSS
						if ($key=='date'||$key=='pubDate'||$key=='title'||$key=='link'){$feed.=$t.$t.$t.$t.'<'.$key.'>'.htmlspecialchars($value).'</'.$key.'>'.$r;}
						elseif($key=='guid'){ $feed.=$t.$t.$t.$t.'<guid isPermaLink="false">'.$value.'</guid>'.$r;}
						else{$feed.=$t.$t.$t.$t.'<'.$key.'><![CDATA['.$value.']]></'.$key.'>'.$r;}
					}
				}
			if ($array['infos']['type']=='atom'){ $feed.=$t.$t.$t.'</entry>'.$r;}else{$feed.=$t.$t.$t.'</item>'.$r;}
		}


	$feed.=$tpl[$array['infos']['type']]['footer'];
	return $feed;
}

// récupération des parametres get

if (isset($_GET['q'])){$query=strip_tags($_GET['q']);}else{exit('pas de query');}
if (isset($_GET['title'])){$title=strip_tags($_GET['title']);}else{$title='GoogolSearch for '.$query;}
if (isset($_GET['nb'])){$nb=strip_tags($_GET['nb']);}else{$nb=20;}

echo array2feed(parse_query($query,$title,$nb));

?>
			
51 - secure - sécuriser une chaine ou un tableau contre le XSS
function secure($var,$level=0){
    // $level=0 > returns text only (no html or script), 1 > text + html (no script), 2 > all content secured with entities
    if (is_array($var)){foreach ($var as $index=>$v){$var[$index]=secure($v,$level);}}
    else if (is_string($var)){
        if ($level==0){$var=strip_tags($var);}
        else if ($level==1){$var=preg_replace('#on[a-z]+ ?= ?["\'].*?["\'](?=[ />])|</?script>|javascript:#i','',$var);}
        else {$var=htmlspecialchars($var);}
    }
    return $var;
}
			
53 - sendmail
function sendmail($to,$subject='message',$msg,$from=null,$format='text/plain'){
	$r="\r\n";$header='';
	$msg=wordwrap($msg, 70,$r);
	if ($format!='text/plain'){$msg=htmlspecialchars($msg);}
	if (!empty($from)){$header.='From: '.$from.$r;}
	$header='Content-Type: text/plain; charset="utf-8"'.$r.'Content-Transfer-Encoding: 8bit'.$r.$header;
	return mail($to,$subject,$msg,$header);
}
			
54 - Zipper un dossier et ses sous-dossiers
// nouvelle archive
$zip = new ZipArchive;

// ouverture
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
   $folder = 'mon_dossier';
   inputfolder: // "goto" apparu en php >= 5.3.0

   // ouvre le dossier
   if ($handle = opendir($folder)) {

      // parcourt les entrées une par unes.
      while (FALSE !== ($entry = readdir($handle))) {

         // on exclu les dossiers parents (..) et courant (.),
         // ainsi que les fichiers dont on n’a pas les droits en lecture
         if ($entry != "." AND $entry != ".." AND is_readable($folder.'/'.$entry)) {

            // si c’est un dossier, on reboucle avec le GOTO
            if (is_dir($folder.'/'.$entry)) {
               // ne surtout pas oublier ceci :)
               $folder =  $folder.'/'.$entry;
               goto inputfolder;
            }

            // on ajoute le fichier (l’arborescence d’origine est conservée)
            $zip->addFile($folder.'/'.$entry, $folder.'/'.$entry);
         }
      }

      // ferme le dossier
      closedir($handle);
   }

   // ferme l’archive ZIP
   $zip->close();

   echo '<p>ok : <a href="test.zip">test.zip</a></p>';
} else {
   echo '<p>échec lors du open()</p>';
}




			
55 - Calendrier
<?php

function afficher_calendrier() {
    $ce_mois_lettres = date('F');
    $jours_semaine = array('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su');

    $premier_jour = mktime('0', '0', '0', date('m'), '1', date('Y'));

    // haut du tableau
    $calendar = '<table id="calendrier">'."\n";
    $calendar.= '<caption>'.$ce_mois_lettres.'</caption>'."\n";
    $calendar.= '<tr><th>'.implode('</th><th>', $jours_semaine).'</th></tr><tr>';

    // un nouveau mois ne commence pas forcément le premier jour de la semaine (lundi)
    $decalage_jour = date('w', $premier_jour-'1');
    if ($decalage_jour > 0) {
        for ($i = 0; $i < $decalage_jour; $i++) {
            $calendar.=  '<td></td>';
        }
    }

    // création du tableau
    $date_t = date('t');
    $date_d = date('d');

    for ($jour = 1; $jour <= $date_t; $jour++) {
        $calendar.= '<td';

        // ajoute une classe CSS sur aujourd'hui
        $calendar .= ($jour == $date_d) ? ' class="active"' : '';

        $calendar.= '>';
        $calendar.= $jour;
        $calendar.= '</td>';
        $decalage_jour++;
        if ($decalage_jour == '7') {
            $decalage_jour = '0';
            $calendar.=  '</tr>'."\n";
            $calendar.= ($jour < $date_d) ? '<tr>' : '';
        }
    }

    // complète le tableau HTML avec des cases vides à la fin
    if ($decalage_jour > '0') {
        for ($i = $decalage_jour; $i < '7'; $i++) {
            $calendar.= '<td></td>';
        }
        $calendar.= '</tr>'."\n";
    }
    $calendar.= '</table>'."\n";

    return $calendar;
}

?>



			
56 - BodyClasses
# Renvoie un attribut class complet (navigateur navigateur+version nom de la page sans extension)
# ex class="Firefox Firefox23 index" 
# utile pour apporter des corrections de style en fonction de la page et de la version du navigateur
# On peut ajouter ses propres classes via cette fonction: BodyClasses('maclasse'); 
function BodyClasses($other_classes=''){    
        $regex='#(msie)[/ ]([0-9])+|(firefox)/([0-9])+|(chrome)/([0-9])+|(opera)/([0-9]+)|(safari)/([0-9]+)|(android)|(iphone)|(ipad)|(blackberry)|(Windows Phone)|(symbian)|(mobile)|(bada])#i';
        preg_match($regex,$_SERVER['HTTP_USER_AGENT'],$resultat);          
        echo ' class="'.preg_replace('#([a-zA-Z ]+)[ /]([0-9]+)#','$1 $1$2',$resultat[0]).' '.basename($_SERVER['PHP_SELF'],'.php').' '.$other_classes.'" ';     
}

			
57 - Lister les pages statiques d'un groupe particulier
<?php $plxShow = plxShow::getInstance();
	if ($plxShow->mode() == 'static') :
    $group='Documentation';
    if (!empty($plxShow->plxMotor->aStats)) {
        foreach($plxShow->plxMotor->aStats as $k => $v) {
            if ($v['group'] == $group) {
                   echo '<a href="?static'.intval($k).'/'.$v['url'].'" class="icone_'.strtolower($v['name']).'">'.$v['name'].'</a>';
             }
         }
    }
endif;?>
			
58 - Encoder les adresses mail
function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )  
{  
    // remplazar aroba y puntos  
    $email = str_replace('@', '@', $email);  
    $email = str_replace('.', '.', $email);  
    $email = str_split($email, 5);  
  
    $linkText = str_replace('@', '@', $linkText);  
    $linkText = str_replace('.', '.', $linkText);  
    $linkText = str_split($linkText, 5);  
      
    $part1 = '<a href="ma';  
    $part2 = 'ilto:';  
    $part3 = '" '. $attrs .' >';  
    $part4 = '</a>';  
  
    $encoded = '<script type="text/javascript">';  
    $encoded .= "document.write('$part1');";  
    $encoded .= "document.write('$part2');";  
    foreach($email as $e)  
    {  
            $encoded .= "document.write('$e');";  
    }  
    $encoded .= "document.write('$part3');";  
    foreach($linkText as $l)  
    {  
            $encoded .= "document.write('$l');";  
    }  
    $encoded .= "document.write('$part4');";  
    $encoded .= '</script>';  
  
    return $encoded;  
}  
			
59 - file_curl_contents
// récupérer un fichier distant avec retour false si inexistant
function file_curl_contents($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,  FALSE);     
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     
	curl_setopt($ch, CURLOPT_URL, $url);     
	if (!ini_get("safe_mode") && !ini_get('open_basedir') ) {curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);}    
	curl_setopt($ch, CURLOPT_MAXREDIRS, 10); 
	curl_setopt($ch, CURLOPT_REFERER, 'http://oudanstoncul.free.fr');// notez le referer "custom"
	$data = curl_exec($ch);     
	curl_close($ch);     
	return $data; 
}  
  
// on peut l'utiliser comme suit:
// if ($contenu=file_curl_contents('http://adresse.com/fichier.txt')){echo $contenu;}else{echo "le fichier n'existe pas!";}
			
61 - get full url of the current page
function full_url()
{
	$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
	$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
	return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
}
			
62 - variables dynamiques (dont le nom est une variable)
(via HollandaisVolant)

Faire des variables dynamiques en JS.
 Un trop dont je ne me sert jamais, mais là ouais.
 
 // En gros, si t’as ça :
 var variable = 'machin';
 var machin = document.getElementById('id');
 
 // on peut faire :
 eval(variable).style.display = 'block';
 
 // variable contient « machin ».
 // en faisant le eval(), c’est comme si le contenu de "variable" devenait une variable. Ici, donc, le #id aura comme display un « block ».
 // Pratique si on n’a pas envie de faire un « getElementById » pour 50 blocs à la fois, mais qu’on peut écrire dans un boucle avec ça.
 
 Ça existe aussi en PHP :
 $var = nombre;
 $nombre = 137;
 $$var = 42;

			
63 - feed2array
# Feed2array 
# @author: bronco@warriordudimanche.net
# @version 0.2
# @license  free and opensource
# @inspired by  http://milletmaxime.net/syndexport/
# @use: $items=feed2array('http://sebsauvage.net/links/index.php?do=rss');

function feed2array($feed,$load=true){
	if ($load){if (!$feed_content=file_get_contents($feed)){return false;}}else{$feed_content=$feed;}

	$flux=array('infos'=>array(),'items'=>array());
	if(preg_match('~<rss(.*)</rss>~si', $feed_content)){$type='RSS';}//RSS ?
	elseif(preg_match('~<feed(.*)</feed>~si', $feed_content)){$type='ATOM';}//ATOM ?
	else return false;//if the feed isn't rss or atom
	$feed_content=utf8_encode($feed_content);
	$flux['infos']['type']=$type;
	if($feed_obj = new SimpleXMLElement($feed_content, LIBXML_NOCDATA))
	{		
		$flux['infos']['version']=$feed_obj->attributes()->version;
		if (!empty($feed_obj->attributes()->version)){	$flux['infos']['version']=(string)$feed_obj->attributes()->version;}
		if (!empty($feed_obj->channel->title)){			$flux['infos']['title']=(string)$feed_obj->channel->title;}
		if (!empty($feed_obj->channel->subtitle)){		$flux['infos']['subtitle']=(string)$feed_obj->channel->subtitle;}
		if (!empty($feed_obj->channel->link)){			$flux['infos']['link']=(string)$feed_obj->channel->link;}
		if (!empty($feed_obj->channel->description)){	$flux['infos']['description']=(string)$feed_obj->channel->description;}
		if (!empty($feed_obj->channel->language)){		$flux['infos']['language']=(string)$feed_obj->channel->language;}
		if (!empty($feed_obj->channel->copyright)){		$flux['infos']['copyright']=(string)$feed_obj->channel->copyright;}
		

		if (!empty($feed_obj->title)){			$flux['infos']['title']=(string)$feed_obj->title;}
		if (!empty($feed_obj->subtitle)){		$flux['infos']['subtitle']=(string)$feed_obj->subtitle;}
		if (!empty($feed_obj->link)){			$flux['infos']['link']=(string)$feed_obj->link;}
		if (!empty($feed_obj->description)){	$flux['infos']['description']=(string)$feed_obj->description;}
		if (!empty($feed_obj->language)){		$flux['infos']['language']=(string)$feed_obj->language;}
		if (!empty($feed_obj->copyright)){		$flux['infos']['copyright']=(string)$feed_obj->copyright;}
		

		if (!empty($feed_obj->channel->item)){	$items=$feed_obj->channel->item;}
		if (!empty($feed_obj->entry)){	$items=$feed_obj->entry;}
		if (empty($items)){return false;}

		//aff($feed_obj);
		foreach ($items as $item){
			$c=count($flux['items']);
			if(!empty($item->title)){		 	$flux['items'][$c]['title'] 	  =	(string)$item->title;}
			if(!empty($item->logo)){		 	$flux['items'][$c]['titleImage']  =	(string)$item->logo;}
			if(!empty($item->icon)){		 	$flux['items'][$c]['icon'] 		  =	(string)$item->icon;}
			if(!empty($item->subtitle)){ 		$flux['items'][$c]['description'] = (string)$item->subtitle;}
			if(!empty($item->link['href'])){ 	$flux['items'][$c]['link']		  = (string)$item->link['href'];}
			if(!empty($item->language)){		$flux['items'][$c]['language']	  = (string)$item->language;}
			if(!empty($item->author->name)){ 	$flux['items'][$c]['author']	  =	(string)$item->author->name;}
			if(!empty($item->author->email)){	$flux['items'][$c]['email'] 	  = (string)$item->author->email;}
			if(!empty($item->updated)){			$flux['items'][$c]['last'] 		  = (string)$item->updated;}
			if(!empty($item->rights)){			$flux['items'][$c]['copyright']	  = (string)$item->rights;}
			if(!empty($item->generator)){		$flux['items'][$c]['generator']	  = (string)$item->generator;}
			if(!empty($item->guid)){			$flux['items'][$c]['guid']	 	  = (string)$item->guid;}
			if(!empty($item->pubDate)){			$flux['items'][$c]['pubDate']	  = (string)$item->pubDate;}
			if(!empty($item->description)){		$flux['items'][$c]['description'] = (string)$item->description;}
			if(!empty($item->summary)){			$flux['items'][$c]['description'] = (string)$item->summary;}
			if(!empty($item->published)){		$flux['items'][$c]['date'] = (string)$item->published;}
			if(!empty($item->update)){			$flux['items'][$c]['update'] = (string)$item->update;}
			if(!empty($item->link)){			$flux['items'][$c]['link'] = (string)$item->link;}
			if(!empty($item->content)){			$flux['items'][$c]['description'] = (string)$item->content;}
			
		}
	}else return false;
	return $flux;
}
			
64 - array2feed
# Array2feed 
# @author: bronco@warriordudimanche.net
# @version 0.1
# @license  free and opensource
# @inspired by  http://milletmaxime.net/syndexport/
# @use: $items=feed2array('http://sebsauvage.net/links/index.php?do=rss');
# @doc:
	# the array must have an index 'infos' and another called 'items'
	#info key
		# for rss type feed, infos must have at least the 'title', 'description', 'guid' keys
		# for atom type feed, infos must have at least the 'title', 'id', 'subtitle', 'link' keys
	# items key => array
		# for rss type feed, each item must have the 'title', 'description', 'pubDate' and 'link' keys
		# for atom type feed, info must have the 'title', 'id', 'updated, 'link' & 'content' keys 

function array2feed($array=null){


	if (!$array){return false;}
	if (empty($array['infos']['type'])){$array['infos']['type']='rss';}else{$array['infos']['type']=strtolower($array['infos']['type']);}
	if (empty($array['infos']['description'])){$array['infos']['description']='';}
	$r="n";$t="t";
	$tpl=array('rss'=>array(),'atom'=>array());
	$tpl['rss']['header']='<?xml version="1.0" encoding="utf-8" ?>'.$r.'<rss version="2.0"  xmlns:content="http://purl.org/rss/1.0/modules/content/">'.$r.$t.'<channel>'.$r;
	$tpl['atom']['header']='<feed xmlns="http://www.w3.org/2005/Atom">'.$r;
	$tpl['rss']['footer']=$t.'</channel></rss>'.$r;
	$tpl['atom']['footer']='</feed>'.$r;
	$tpl['rss']['content-type']='Content-Type: application/rss+xml';
	$tpl['atom']['content-type']='Content-Type: application/atom+xml;charset=utf-8';

	header($tpl[$array['infos']['type']]['content-type']);
	$feed=$tpl[$array['infos']['type']]['header'];
		//create the feed's info content
		foreach($array['infos'] as $key=>$value){
			if ($array['infos']['type']=='atom'){ // ATOM
				if ($key=='link'){$feed.=$t.$t.'<link href="'.$value.'" rel="self" type="application/atom+xml"/>'.$r;}
				elseif ($key=='author'){$feed.=$t.$t.'<author><name>'.$value.'</name></author>'.$r;}
				elseif ($key=='licence'){$feed.=$t.$t.'<'.$key.' href="'.$value.'" rel="license"/>'.$r;} // in atom feed, licence is the link to the licence type
				elseif ($key!='version'&&$key!='type'){$feed.=$t.$t.'<'.$key.'>'.$value.'</'.$key.'>'.$r;}
			}else{ // RSS
				if ($key!='version'&&$key!='type'){$feed.=$t.$t.'<'.$key.'>'.$value.'</'.$key.'>'.$r;}
			}
		}

		//then the items content
		foreach ($array['items'] as $item){
			if ($array['infos']['type']=='atom'){ $feed.=$t.$t.$t.'<entry>'.$r;}else{$feed.=$t.$t.$t.'<item>'.$r;}
				foreach($item as $key=>$value){
					if ($array['infos']['type']=='atom'){ // ATOM
						if ($key=='link'){$feed.=$t.$t.$t.$t.'<link href="'.$value.'" rel="alternate" type="text/html"/>'.$r;}
						elseif ($key=='content'){$feed.=$t.$t.$t.$t.'<content type="text">'.htmlspecialchars($value).'</content>'.$r;}
						else{$feed.=$t.$t.$t.$t.'<'.$key.'>'.$value.'</'.$key.'>'.$r;}
					}else{ // RSS
						if ($key=='date'||$key=='pubDate'||$key=='title'||$key=='link'){$feed.=$t.$t.$t.$t.'<'.$key.'>'.htmlspecialchars($value).'</'.$key.'>'.$r;}
						elseif($key=='guid'){ $feed.=$t.$t.$t.$t.'<guid isPermaLink="false">'.$value.'</guid>'.$r;}
						else{$feed.=$t.$t.$t.$t.'<'.$key.'><![CDATA['.$value.']]></'.$key.'>'.$r;}
					}
				}
			if ($array['infos']['type']=='atom'){ $feed.=$t.$t.$t.'</entry>'.$r;}else{$feed.=$t.$t.$t.'</item>'.$r;}
		}


	$feed.=$tpl[$array['infos']['type']]['footer'];
	return $feed;
}

$array=array(
	'infos'=>array(
			'type'=>'rss',
			'description'=>'Ceci est le test ultime de la mort',
			'title'=>'test de création de flux rss',
			'link'=>'http://www.warriordudimanche.net',
		),
	'items'=>array(
		0=>array(
				'description'=>'Ceci est le premier item du flux',
				'title'=>'item 1 : le titre',
				'link'=>'http://www.warriordudimanche.net',
				'guid'=>'http://www.warriordudimanche.net#1',
				'pubDate'=>@date('r'),// Be carefull, the rss pubDate format is specific ! RFC 2822 (see http://www.faqs.org/rfcs/rfc2822.html)
			),
		1=>array(
				'description'=>'Ceci est le second item du flux',
				'title'=>'item 2 : le retour',
				'link'=>'http://www.warriordudimanche.net',
				'guid'=>'http://www.warriordudimanche.net#2',
				'pubDate'=>@date('r'),
			),
		2=>array(
				'description'=>'Ceci est le troisième item du flux',
				'title'=>'item 3 : la revanche',
				'link'=>'http://www.warriordudimanche.net',
				'guid'=>'http://www.warriordudimanche.net#3',
				'pubDate'=>@date('r'),
			),

		)
	);



echo array2feed($array);
			
65 - Détecter efficacement UTF-8
function detectUTF8($string)
{
    return preg_match('%(?:
        [xC2-xDF][x80-xBF]             # non-overlong 2-byte
        |xE0[xA0-xBF][x80-xBF]        # excluding overlongs
        |[xE1-xECxEExEF][x80-xBF]{2} # straight 3-byte
        |xED[x80-x9F][x80-xBF]        # excluding surrogates
        |xF0[x90-xBF][x80-xBF]{2}     # planes 1-3
        |[xF1-xF3][x80-xBF]{3}         # planes 4-15
        |xF4[x80-x8F][x80-xBF]{2}     # plane 16
        )+%xs', 
    $string);
}
			
66 - Détecter les navigateurs mobiles isMobileBrowser
function isMobileBrowser() {  
      return stristr($_SERVER['HTTP_USER_AGENT'],'iPhone') ||
      stristr($_SERVER['HTTP_USER_AGENT'],'iPod') || 
      stristr($_SERVER['HTTP_USER_AGENT'],'android');
}
			
67 - stripAccents - remplacer avec accents par sans accents
function stripAccents($string){	
	$a=explode(' ','à á â ã ä ç è é ê ë ì í î ï ñ ò ó ô õ ö ù ú û ü ý ÿ À Á Â Ã Ä Ç È É Ê Ë Ì Í Î Ï Ñ Ò Ó Ô Õ Ö Ù Ú Û Ü Ý');
	$b=explode(' ','a a a a a c e e e e i i i i n o o o o o u u u u y y A A A A A C E E E E I I I I N O O O O O U U U U Y');
	return str_replace($a,$b,$string);
}
			
68 - get_favicon
function get_favicon($url){ 
	// récupère la favicon du site si possible et la stocke en local 
	// si elle n'est pas déjà sur le serveur, sinon, renvoie le chemin
	// vers la version locale
        $id=sha1($url); // génère un nom de favicon local lié à l'url
	$file='CHEMIN_LOCAL_FAVICON/'.$id.'.png';
	$defaultfavicon='design/img/default_favicon.png';
	if ($url==''){return $defaultfavicon;}
	if (!is_file($file)){
		@$header=file_get_contents($url, NULL, NULL, 0, 3000);
		if ($header){
			if (preg_match('#<link +rel=["'].*icon["'].+href="([^"]+)|<link.+href="([^"]+).+rel=["'].*icon["']#',$header,$r)>0){
				// favicon trouvée > on récupère et on sauve en local
				if ($r[1]==''){$f=$r[2];}else{$f=$r[1];}
				@$img=file_get_contents($f);
				$url=pathinfo($url ,PATHINFO_DIRNAME );
				if(!$img){@$img=file_get_contents($url.'/'.$f);}
				if(!$img){@$img=file_get_contents($url.$f);}
				if ($img){
					file_put_contents($file,$img);
					return $file;
				}
			}
		}
		// impossible de récupérer la favicon > icone par défaut
		return $defaultfavicon;
	}else{
		return $file;
	}
}
			
69 - bloquer la diffusion des erreurs et réagir (même les fatales)
ini_set('display_errors', '0');         
register_shutdown_function('shutdown');
function shutdown() 
{ 
       $error = error_get_last();
       if ($error['type'] === E_ERROR) {

      //do your shutdown stuff here
      //be care full do not call any other function from within shutdown function
      //as php may not wait until that function finishes
      //its a strange behavior. During testing I realized that if function is called 
      //from here that function may or may not finish and code below that function
      //call may or may not get executed. every time I had a different result. 

      // e.g.

      other_function();

      //code below this function may not get executed

       } 

} 
			
70 - Fonction d'arrêt et de débuggage: AFF()
function aff($a,$stop=true){echo 'Arret a la ligne '.__LINE__.' du fichier '.__FILE__.'<pre>';var_dump($a);echo '</pre>';if ($stop){exit();}}

			
73 - fonction de pagination
/**
 * Generate an array of pagination link where the key is a page number
 * and the value is a type of link (current page, normal link, first/last page link)
 * @param  integer $currentPage   the current displayed page
 * @param  integer $totalPages    the total number of pages (can be replaced by the two following params)
 * @param  integer $itemPerPage   the number of item displayed on each page
 * @param  integer $totalItems    the total number of existing items
 * @param  integer $nbPagesAround the maximum number of links (excluding first/last) that should be displayed before or after the current page
 * @return array                  the pagination array (key = page to link to, value = type of link)
 */
function generatePagination(
    $currentPage,
    $totalPages = 0,
    $itemPerPage = 0,
    $totalItems = 0,
    $nbPagesAround = 2
) {
    $pagination = array();
 
    if($totalPages == 0) {
        if($itemPerPage == 0 || $totalItems == 0) {
            return false;
        } else {
            $totalPages = (int)ceil($totalItems / $itemPerPage);
        }
    }
 
    if($currentPage > $nbPagesAround + 2) {
        $pagination[1] = self::PAGINATION_FIRST;
    } elseif($currentPage > $nbPagesAround + 1) {
        $pagination[1] = self::PAGINATION_LINK;
    }
    for($i = ($currentPage - $nbPagesAround); $i < $currentPage; $i++) {
        if($i > 1 || ($i == 1 && $currentPage <= $nbPagesAround + 1)) {
            $pagination[$i] = self::PAGINATION_LINK;
        }
    }
    $pagination[$currentPage] = self::PAGINATION_CURRENT;
    for($i = ($currentPage + 1); $i < ($currentPage + $nbPagesAround + 1); $i++) {
        if($i < $totalPages
            || ($i == $totalPages && $currentPage >= $totalPages - $nbPagesAround)
        ) {
            $pagination[$i] = self::PAGINATION_LINK;
        }
    }
    if($currentPage < ($totalPages - $nbPagesAround - 1)) {
        $pagination[$totalPages] = self::PAGINATION_LAST;
    } elseif($currentPage < ($totalPages - $nbPagesAround)) {
        $pagination[$totalPages] = self::PAGINATION_LINK;
    }
 
    // ksort($pagination);
 
    return $pagination;
}
			
75 - Recherche et récup d'infos via allocine: sans API !
<?php
$config=array(
	// Ces regexes pourront être corrigées facilement en cas de changement de la page allocine
	'query_string'=>'http://www.allocine.fr/recherche/1/?q=',
	'base_url'=>'http://www.allocine.fr/',
	'regex_get_links_results'=>'<td[^<]+<a href=["'](/film/fichefilm_gen_cfilm=[^'"]+)',
	'regex_url_image'=>'(http://fr.web.img[^"']+)|(http://images.allocine.fr/[^"']+)',
	'regex_url_image_capture_dim'=>'([a-z])_[0-9]+_[0-9]+',
	'regex_url_image_redim'=>'$1_640_400',
	'regex_get_titre'=>'"label":"([^^]+)","fanCount"', 
	'regex_get_genre'=>'itemprop="genre">([^<]+)', 
	'regex_get_description'=>'itemprop="description">([^<]+)', 
	'regex_get_note'=>'<span class="stars n([^"]+)',
	'regex_get_actors'=>'<span itemprop="name">([^<]+)',
);
function search2array($query){
	global $config;
	//charge la page de recherche d'allocine, retrouve les liens de résultat
	$query=$config['query_string'].str_replace(' ','+',$query);
	$search_page=file_get_contents($query);
	preg_match_all('#'.$config['regex_get_links_results'].'#', $search_page, $results);
	if (count($results[1])>0){return $results[1];}else{return false;}
}

function movielink2array($url){
	global $config;
	//charge la page de la fiche passée en lien, retourne les infos
	$page=file_get_contents($config['base_url'].$url);
	$verif=0;
	$verif+=preg_match('#'.$config['regex_get_titre'].'#', $page, $title);
	$verif+=preg_match('#'.$config['regex_get_genre'].'#', $page, $genre);
	$verif+=preg_match('#'.$config['regex_get_note'].'#', $page, $note);
	$verif+=preg_match('#'.$config['regex_get_description'].'#', $page, $description);
	$verif+=preg_match('#'.$config['regex_url_image'].'#', $page, $image);	
	$verif+=preg_match_all('#'.$config['regex_get_actors'].'#', $page, $actors);

	$image=preg_replace('#'.$config['regex_url_image_capture_dim'].'#',$config['regex_url_image_redim'],$image[0]);
	$result=array();
	$result['movie_actors']=implode(', ',$actors[1]);
	$result['movie_image']=$image;
	$result['movie_allocine_url']=$url;
	if(is_array($title)&&isset($title[1])){$result['movie_title']=$title[1];}else{$result['movie_title']='';}
	if(is_array($note)&&isset($note[1])){$result['movie_stars']=$note[1];}else{$result['movie_stars']=0;}
	if(is_array($genre)&&isset($genre[1])){$result['movie_type']=$genre[1];}else{$result['movie_type']='';}
	if(is_array($description)&&isset($description[1])){$result['movie_description']=$description[1];}else{$result['movie_description']='';}
	
	if (count($result)>0){return $result;}else{return false;}
}

function url_array2list($array=array(),$tpl='<ul><li><img src="movie_image"/></li><li>movie_title</li><li>movie_type</li><li>movie_stars</li><li>movie_actors</li><li>movie_description</li><li><a href="movie_allocine_url">On allocine</a></li></ul>'){
	$list='';
	foreach($array as $url){
		$page=movielink2array($url);

		$list.=str_replace(array_keys($page),array_values($page),$tpl);
	}
	return $list;
}

//ex:
echo url_array2list(search2array('heros'));

?> 
			
76 - n_print: tracer les variables sans exit();
<?php
/**
* Améliore la sortie print
*
* @author Tatane http://www.tatane.info/index.php/print_rn
* @author http://www.blog.cactuscrew.com/77-print_rn.html
* @param $data (array) tableau ou variable à examiner
* @param $name (string) nom a afficher
* @return false affiche les clef valeur du tableau $data
* @example n_print($array, 'Tableau de valeur');
*/
function n_print($data, $name = '') {
$aBackTrace = debug_backtrace();
echo '<h2>', $name, '</h2>';
echo '<fieldset style="border: 1px solid orange; padding: 5px;color: #333; background-color: #fff;">';
echo '<legend style="border:1px solid orange;padding: 1px;background-color:#eee;color:orange;">', basename($aBackTrace[0]['file']), ' ligne => ', $aBackTrace[0]['line'], '</legend>';
echo '<pre>', htmlentities(print_r($data, 1)), '</pre>';
echo '</fieldset><br />';
}
?>
			
77 - Fonctions de cache
function lis_dans_cache($fichier,$returnvar=null,$echoresult=null,$unserialize=true){
  //lit le cache
  if (file_exists('temp/'.$fichier)){
    $var=file_get_contents('temp/'.$fichier);
    if ($unserialize==true){$var=unserialize($var);}
    if ($echoresult==true){echo $var;return true;}
    if ($returnvar==true){return $var;} 
  }else{return false;}
}
function ecris_dans_cache($fichier,$var,$serialize=true){
  //ecrit le cache
  if ($serialize==true){$var=serialize($var);}
  file_put_contents('temp/'.$fichier,$var);
}
function clear_cache(){
  $fs=glob('temp/*');
  foreach ($fs as $file){
      unlink ($file);
  }
}
function start_cache(){
  ob_start();
}
function end_cache($fichier,$returnvar=null,$echoresult=null){
  $var=ob_get_clean();
  if ($echoresult==true){ecris_dans_cache($fichier,$var,false);echo $var;return true;}
  if ($returnvar==true){ecris_dans_cache($fichier,$var,true);return unserialize($var);}
  
}


//Stocker le résultat d'une portion de code

          if (!$var=lis_dans_cache('nomdufichierdecache',true,false,false)){// pas dans le cache
            start_cache();
              list_matching_snippets($titre,$tagonly);
            end_cache'nomdufichierdecache',false,true);
          }else{
            echo $var;
          }

//Stocker une variable
if (!$var=lis_dans_cache('tagcloud',true,false,true)){
  $tags=list_tags();
  $taglist=array();
  foreach($tags as $tag){
    $taglist[]=$tag['x'];
  }
  natcasesort($taglist);
  
  ecris_dans_cache('tagcloud',$taglist,true);
  ecris_dans_cache('tags',$tags,true);
}else{
  $taglist=$var;
  $tags=lis_dans_cache('tags',true);
}


			
78 - auto_error_handler
<?php
# Error handler by bronco@warriordudimanche.net #################
function showline($line,$file){
	$f=file($file);$r='';
	for ($l=$line-2;$l<$line+2;$l++){
		if (isset($f[$l])){
			if ($l==$line-1){
				$r.='<em style="color:white;text-shadow:0 0 2px black"><strong>'.$l.' >> </strong> '.$f[$l].'</em>';
			}else{
				$r.='<strong>'.$l.' >> </strong> '.$f[$l];
			}
		}
	}
	return $r;
}
function error_handler($number, $message, $file, $line, $vars){
	echo "
		<div style='word-wrap: break-word;Box-sizing: Border-box ;border-radius:5px;padding:15px;margin-bottom:20px;box-shadow:0 2px 1px maroon;font-family:courier;position:absolute;top:0;left:0;background-color:rgba(255,100,100,0.2);width:100%;height:auto;position:relative;min-width:320px;'>
			<h1 style='color:red;border-radius:5px;background-color:pink;padding:5px;box-shadow:0 2px 1px maroon'>Erreur $number</h1>
			<p style=''> <em>$message </em> a la ligne <strong style='font-size:24px'>$line</strong> dans le fichier <strong style='font-size:24px'>file: $file.</strong></p>
			
			<pre style='font-weight:bold;padding:20px;margin-left:10px;color:orange;text-shadow:0 1px 1px maroon;box-shadow:inset 0 2px 1px maroon;border-radius:5px;background-color:red;'><code>".showline($line,$file)."</pre></code>
			<h1 style='color:red;border-radius:5px;background-color:pink;padding:5px;box-shadow:0 2px 1px maroon'>Variables</h1>
			<pre style='overflow:scroll;height:200px;'>";
			var_dump($vars) ;
			echo "</pre>
			<a style='display:block;text-align:right;font-size:14px;color:maroon;text-decoration:none;font-weight:bold;font-styl:italic;' href='http://warriordudimanche.net/'>Error handler par warriordudimanche.net</a>
		</div>";

	if ( ($number !== E_NOTICE) && ($number < 2048) ) {die("Erreur fatale.");}
}

set_error_handler('error_handler');
#################################################################
?>
			
79 - Lire/écrire dans un fichier en compressant/décompressant en une instruction
#En PHP, il y a plusieurs moyens pour lire et écrire dans un fichier (fopen). De même pour en compresser son contenu (gzcompress).
#Seulement, vous pouvez vous simplifier la vie en utilisant UNE seule instruction pour stocker du contenu sous forme compressée :

file_put_contents("compress.zlib://$filename", $content);

#Ensuite, pour lire ce fichier compressé, UNE instruction également :

$content = file_get_contents("compress.zlib://$filename");

#"compress.zlib://" est en fait ce qu'on appelle un wrapper ; il en existe plusieurs autres en PHP. Celui-ci permet de dire que le fichier sera compressé grâce à la bibliothèque Zlib.

#ATTENTION : avec file_get_contents(), si la lecture échoue, il renvoie le booléen "false" ! Or, il est indispensable de bien tester le retour à l'aide de l'égalité de #type (=== ou !==), car si le fichier contient, par exemple, 0 et que vous testez avec l'égalité simple (== ou !=), alors il considérera que c'est faux, donc que la #lecture a échoué ! C'est normal : 0 == false (même valeur) mais 0 !== false (pas le même type) !

#Donc il faut tester comme suit : if ($content !== false) { //OK, do something... }
			
80 - générer une chaine aléatoire lisible par un humain
/************** 
*@length - length of random string (must be a multiple of 2) 
**************/  
function readable_random_string($length = 6){  
    $conso=array("b","c","d","f","g","h","j","k","l",  
    "m","n","p","r","s","t","v","w","x","y","z");  
    $vocal=array("a","e","i","o","u");  
    $password="";  
    srand ((double)microtime()*1000000);  
    $max = $length/2;  
    for($i=1; $i<=$max; $i++)  
    {  
    $password.=$conso[rand(0,19)];  
    $password.=$vocal[rand(0,4)];  
    }  
    return $password;  
}  
			
81 - Parser du XML
//xml string  
$xml_string="<?xml version='1.0'?> 
<users> 
   <user id='398'> 
      <name>Foo</name> 
      <email>foo@bar.com</name> 
   </user> 
   <user id='867'> 
      <name>Foobar</name> 
      <email>foobar@foo.com</name> 
   </user> 
</users>";  
  
//load the xml string using simplexml  
$xml = simplexml_load_string($xml_string);  
  
//loop through the each node of user  
foreach ($xml->user as $user)  
{  
   //access attribute  
   echo $user['id'], '  ';  
   //subnodes are accessed by -> operator  
   echo $user->name, '  ';  
   echo $user->email, '<br />';  
}  
			
84 - Forcer le téléchargement d'un fichier
/******************** 
*@file - path to file 
*/  
function force_download($file)  
{  
    if ((isset($file))&&(file_exists($file))) {  
       header("Content-length: ".filesize($file));  
       header('Content-Type: application/octet-stream');  
       header('Content-Disposition: attachment; filename="' . $file . '"');  
       readfile("$file");  
    } else {  
       echo "No file selected";  
    }  
}  
			
85 - Créer un nuage de tags
function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )  
{  
    $minimumCount = min($data);  
    $maximumCount = max($data);  
    $spread       = $maximumCount - $minimumCount;  
    $cloudHTML    = '';  
    $cloudTags    = array();  
  
    $spread == 0 && $spread = 1;  
  
    foreach( $data as $tag => $count )  
    {  
        $size = $minFontSize + ( $count - $minimumCount )   
            * ( $maxFontSize - $minFontSize ) / $spread;  
        $cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px'   
        . '" class="tag_cloud" href="#" title="'' . $tag  .  
        '' returned a count of ' . $count . '">'   
        . htmlspecialchars( stripslashes( $tag ) ) . '</a>';  
    }  
      
    return join( "n", $cloudTags ) . "n";  
}  
/************************** 
****   Sample usage    ***/  
$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,   
    'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42,   
    'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30,   
    'Extract' => 28, 'Filters' => 42);  
echo getCloud($arr, 12, 36);  
			
86 - Ajouter un gravatar
/****************** 
*@email - Email address to show gravatar for 
*@size - size of gravatar 
*@default - URL of default gravatar to use 
*@rating - rating of Gravatar(G, PG, R, X) 
*/  
function show_gravatar($email, $size, $default, $rating)  
{  
    echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).  
        '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px"  
        height="'.$size.'px" />';  
}  
			
87 - Tronquer une chaine entre les mots
// Original PHP code by Chirp Internet: www.chirp.com.au   
// Please acknowledge use of this code by including this header.   
function myTruncate($string, $limit, $break=".", $pad="...") {   
    // return with no change if string is shorter than $limit    
    if(strlen($string) <= $limit)   
        return $string;   
      
    // is $break present between $limit and the end of the string?    
    if(false !== ($breakpoint = strpos($string, $break, $limit))) {  
        if($breakpoint < strlen($string) - 1) {   
            $string = substr($string, 0, $breakpoint) . $pad;   
        }   
    }  
    return $string;   
}  
/***** Example ****/  
$short_string=myTruncate($long_string, 100, ' ');
			
88 - Zipper des fichiers
/* creates a compressed zip file */  
function create_zip($files = array(),$destination = '',$overwrite = false) {  
    //if the zip file already exists and overwrite is false, return false  
    if(file_exists($destination) && !$overwrite) { return false; }  
    //vars  
    $valid_files = array();  
    //if files were passed in...  
    if(is_array($files)) {  
        //cycle through each file  
        foreach($files as $file) {  
            //make sure the file exists  
            if(file_exists($file)) {  
                $valid_files[] = $file;  
            }  
        }  
    }  
    //if we have good files...  
    if(count($valid_files)) {  
        //create the archive  
        $zip = new ZipArchive();  
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {  
            return false;  
        }  
        //add the files  
        foreach($valid_files as $file) {  
            $zip->addFile($file,$file);  
        }  
        //debug  
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;  
          
        //close the zip -- done!  
        $zip->close();  
          
        //check to make sure the file exists  
        return file_exists($destination);  
    }  
    else  
    {  
        return false;  
    }  
}  
/***** Example Usage ***/  
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');  
create_zip($files, 'myzipfile.zip', true);  
			
89 - Rendre les liens d'une string clicables
function makeClickableLinks($text) {  
 $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',  
 '<a href="1">1</a>', $text);  
 $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',  
 '1<a href="http://2">2</a>', $text);  
 $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',  
 '<a href="mailto:1">1</a>', $text);  
  
return $text;  
} 
			
91 - Parser le DOM via php (lib)
/*
A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way!
Require PHP 5+.
Supports invalid HTML.
Find tags on an HTML page with selectors just like jQuery.
Extract contents from HTML in a single line.
*/

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';
			
93 - Email les erreurs au lieu de les afficher (handler)

// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
	$email = "
		<p>An error ($number) occurred on line
		<strong>$line</strong> and in the <strong>file: $file.</strong>
		<p> $message </p>";

	$email .= "<pre>" . print_r($vars, 1) . "</pre>";

	$headers = 'Content-type: text/html; charset=iso-8859-1' . "rn";

	// Email the error to someone...
	error_log($email, 1, 'you@youremail.com', $headers);

	// Make sure that you decide how to respond to errors (on the user's side)
	// Either echo an error message, or kill the entire project. Up to you...
	// The code below ensures that we only "die" if the error was more than
	// just a NOTICE.
	if ( ($number !== E_NOTICE) && ($number < 2048) ) {
		die("There was an error. Please try again later.");
	}
}

// We should use our custom function to handle errors.
set_error_handler('nettuts_error_handler');

// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;
			
94 - Récupérer les derniers Tweets
<?php // import & display latest tweet
$username = "perishable";
$feed = "http://search.twitter.com/search.atom?q=from:".$username."&rpp=2";
// $prefix = '<h3>Perishable Press</h3>';
// $suffix = '<p><a href="http://twitter.com/'.$username.'">Follow me on Twitter</a>';
function parse_feed($feed) {
    $stepOne = explode('<content type="html">', $feed);
    $stepTwo = explode('</content>', $stepOne[1]);
    $tweet = $stepTwo[0];
    $tweet = str_replace("<", "<", $tweet);
    $tweet = str_replace(">", ">", $tweet);
    return $tweet;
}
$latest_tweet = file_get_contents($feed);
// echo stripslashes($prefix) . parse_feed($latest_tweet) . stripslashes($suffix);
echo parse_feed($latest_tweet);
?>
			
95 - Sécuriser des chaines
function cleanInput($input) {
 
 $search = array(
  '@<script[^>]*?>.*?</script>@si',  // Strip out javascript
  '@<[/!]*?[^<>]*?>@si',      // Strip out HTML tags
  '@<style[^>]*?>.*?</style>@siU',  // Strip style tags properly
  '@<![sS]*?--[ tnr]*>@'     // Strip multi-line comments
 );
 
  $output = preg_replace($search, '', $input);
  return $output;
 }

function sanitize($input) {
  if (is_array($input)) {
    foreach($input as $var=>$val) {
      $output[$var] = sanitize($val);
    }
  }
  else {
    if (get_magic_quotes_gpc()) {
      $input = stripslashes($input);
    }
    $input = cleanInput($input);
    $output = mysql_real_escape_string($input);
  }
  return $output;
}

// Usage:
$bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
 $good_string = sanitize($bad_string);
 // $good_string returns "Hi! It's a good day!"

 // Also use for getting POST/GET variables
 $_POST = sanitize($_POST);
 $_GET = sanitize($_GET);
			
96 - Trouver la couleur dominante d'une image
Determine the dominant color of an image
This code will be super useful for people managing images or photography website. With it, you can analyze any image and get its dominant color (R, G, or B).

$i = imagecreatefromjpeg("image.jpg");

for ($x=0;$x<imagesx($i);$x++) {
    for ($y=0;$y<imagesy($i);$y++) {
        $rgb = imagecolorat($i,$x,$y);
        $r   = ($rgb >> 16) & 0xFF;
        $g   = ($rgb >>  & 0xFF;
        $b   = $rgb & 0xFF;

        $rTotal += $r;
        $gTotal += $g;
        $bTotal += $b;
        $total++;
    }
}

$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);
			
97 - Récupérer l'URL
function getUrl() {
 $url = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
 $url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
 $url .= $_SERVER["REQUEST_URI"];
 return $url;
}
			
98 - Liens cliquables
function liens_cliquables($url){
  $in=array(
  '`((?:https?|ftp)://S+)(s|z)`',
  '`((?<!//)(www.)S+)(s|z)`');
  $out=array(
  '<a href="$1" target="_blank">$1</a>&nbsp;',
  '&nbsp;<a href="http://$1" target="_blank">$1</a>&nbsp;');
  return preg_replace($in,$out,$url);
}
			
99 - Récuperer le contenu d'une page Web
noter l'utilisation de file qui crée un tableau avec chaque ligne du fichier dans une clé du tableau

function getCode($url){
$code = '';
$lines = file($url);
foreach ($lines as $line_num => $line) {
  $code.= "<div style='background-color:#".($line_num%2==0?'FEFFF2':'FDFFCE').";font-family:Verdana;font-size:11px;border:1px solid #cecece;padding:3px;'>".
  "<h1 style='background-color:#ffffff;padding:3px;font-family:Verdana;font-size:10px;float:left;margin:3px;margin-right:10px;border:1px solid #cecece;'>{$line_num}</h1>" .
  "<div style='margin-top:5px;'>".htmlspecialchars($line) ."</div><div style='clear:left;'></div>".
  "</div>";
}
return $code;
}


echo getCode('http://blog.idleman.fr');
			
100 - Sécuriser GET et POST
$_ = array();
foreach($_POST as $key=>$val){
$_[$key]=mysql_escape_string(htmlentities($val));
}
foreach($_GET as $key=>$val){
$_[$key]=mysql_escape_string(htmlentities($val));
}

utilisation:
echo $_['MaVariablePostOuGet'];
			
101 - Unzip
function unzip_file($file, $destination){
	// create object
	$zip = new ZipArchive() ;
	// open archive
	if ($zip->open($file) !== TRUE) {
		die ('Could not open archive');
	}
	// extract contents to destination directory
	$zip->extractTo($destination);
	// close archive
	$zip->close();
	echo 'Archive extracted to directory';
}
			
102 - Zipper un dossier récursivement
function Zip($source, $destination)
{
  if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
  }

  $zip = new ZipArchive();
  if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
  }

  $source = str_replace('', '/', realpath($source));

  if (is_dir($source) === true)
  {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
      $file = str_replace('', '/', $file);

      // Ignore "." and ".." folders
      if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
        continue;

      $file = realpath($file);

      if (is_dir($file) === true)
      {
        $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
      }
      else if (is_file($file) === true)
      {
        $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
      }
    }
  }
  else if (is_file($source) === true)
  {
    $zip->addFromString(basename($source), file_get_contents($source));
  }

  return $zip->close();
}

Call it like this:

Zip('/folder/to/compress/', './compressed.zip');