Results for fonctions : 83

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 (╯°□°)╯︵ ┻━┻');

}
			
3 - no accents - js
function strNoAccent(a) {
  var b="áàâäãåçéèêëíïîìñóòôöõúùûüýÁÀÂÄÃÅÇÉÈÊËÍÏÎÌÑÓÒÔÖÕÚÙÛÜÝ",
      c="aaaaaaceeeeiiiinooooouuuuyAAAAAACEEEEIIIINOOOOOUUUUY",
      d="";
  for(var i = 0, j = a.length; i < j; i++) {
    var e = a.substr(i, 1);
    d += (b.indexOf(e) !== -1) ? c.substr(b.indexOf(e), 1) : e;
  }
  return d;
}
			
4 - fonction de «bionic reading»
const e = document.getElementById("edit"), r = document.getElementById("read");
const u = () => r.innerHTML = e.innerHTML.split(" ").map(w => `<b>${w.split("").slice(0,Math.ceil(w.length/2)).join("")}</b>${w.split("").slice(Math.ceil(w.length / 2),w.length).join("")} `).join(" ");
u();
e.addEventListener("input", u);

/* kodun orjinal halini de bırakayım da belki birinin işine yarar
const editor = document.getElementById("edit");
const reader = document.getElementById("read");

const updateContent = (e) => {
  const words = editor.innerHTML.split(" ");
  const edited = [];
  words.forEach((word, index) => {
    const wordSplit = word.split("");
    const boldTo = Math.ceil(word.length / 2);
    const editedWord = `<b>${wordSplit.slice(0,boldTo).join("")}</b>${wordSplit.slice(boldTo,word.length).join("")} `;
    edited.push(editedWord);
  });
  reader.innerHTML = edited.join("");
}

(() => {
  updateContent(); // init
  editor.addEventListener("input", updateContent);
})()
*/
			
5 - Vérifier la validité des liens ayant la classe «checkLink»
# Vérifie les URL a/img etc ayant la classe checkLinks
# ou les URL des a/img contenus dans un objet ayant la classe checkLinks
# Ajoute une classe status200, status404 etc (en gros, «statusCODE_DE_REPONSE»

function checkLinks(nodelist){
	function checkUrl(link){
		return fetch(link).then(function(response){		
			return response.status;
		}).catch(function(error){
			return error.status;
		});
	}
	if (!nodelist){
		checkLinks(document.querySelectorAll('.checkLink'));
		return;
	}
	for (let obj of nodelist){
		if (obj.tagName=="A"){
			checkUrl(obj.href).then(function(response){obj.classList.add("status"+response);});
		}else if (obj.hasAttribute("src")){
			checkUrl(obj.src).then(function(response){obj.classList.add("status"+response);});
		}else{
			checkLinks(obj.querySelectorAll("*[href],*[src]"));
		}
	}
}
checkLinks();

# on peut styler les classes:
<style type="text/css">
	.status200{color:green}
	.status404{color:violet}
	.status500{color:red}
</style>
			
6 - 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');

			
8 - 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;
    }
			
9 - How can you encode a string to Base64 in JavaScript? - Stack Overflow
/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

// public method for encoding
encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = Base64._utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
},

// public method for decoding
decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

        enc1 = this._keyStr.indexOf(input.charAt(i++));
        enc2 = this._keyStr.indexOf(input.charAt(i++));
        enc3 = this._keyStr.indexOf(input.charAt(i++));
        enc4 = this._keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }

    }

    output = Base64._utf8_decode(output);

    return output;

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
},

// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

}
			
10 - copier dans le presse-papier
function copy(text) {     if (window.clipboardData && window.clipboardData.setData) {         // IE specific code path to prevent textarea being shown while dialog is visible.         return clipboardData.setData("Text", text);       } else {         var textarea = document.createElement("textarea");         textarea.textContent = text;         textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.         document.body.appendChild(textarea);         textarea.select();         try {             return document.execCommand("copy");  // Security exception may be thrown by some browsers.         } catch (ex) {             console.warn("Copy to clipboard failed.", ex);             return false;         } finally {             document.body.removeChild(textarea);         }     } }
			
11 - ini_load
	def ini_load(self,ini_file):
		if not os.path.isfile(ini_file): return false
		cfg={}
		ini_str=file_get_contents(ini_file)
		ini=re.findall('(?P<var>[a-zA-Z0-9_]*?)=\"(?P<value>[^\"]*?)\"',ini_str)
		for key,val in enumerate(ini):
			cfg[ini[key][0]]=ini[key][1]
		self.cfg=cfg
		

# syntaxe des variables
# folder_path="test/"
			
12 - no_accents
def no_accents(string):
	replacements=[
		(u"é","e"),
		(u"ê","e"),
		(u"è","e"),
		(u"ë","e"),
		(u"ô","o"),
		(u"ó","o"),
		(u"ù","u"),
		(u"ú","u"),
		(u"û","u"),
		(u"ü","u"),
		(u"î","i"),
		(u"ï","i"),
		(u"í","i"),
		(u"â","a"),
		(u"à","a"),
		(u"á","a"),
		(u"ä","a"),
		(u"ñ","n")
	]
	for a, b in replacements:
		string = string.replace(a, b)
	return string
			
13 - get asynchrone avec retour (avec les promises)
function getHTTP(url) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.onload = function() {
            if (this.status >= 200 && this.status < 300) {
                resolve(xhr.response);
            }
        };
        xhr.open("GET", url);
        xhr.send();
    });
}

getHTTP("https://www.google.fr")
.then(function (response) {
    // On récupère le resultat de la requête dans la varible "response"
    console.log(response)
})
			
14 - Récupérer le texte sélectionné en JS
function getSelected() {
	if(window.getSelection) { return window.getSelection(); }
	else if(document.getSelection) { return document.getSelection(); }
	else {
		var selection = document.selection && document.selection.createRange();
		if(selection.text) { return selection.text; }
		return false;
	}
	return false;
}
			
16 - 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');
  }
}

			
17 - ITALIC™ » Générer un password en Javascript
<script type="text/javascript">

    function generer_password(champ_cible) {
        var ok = 'azertyupqsdfghjkmwxcvbn23456789AZERTYUPQSDFGHJKMWXCVBN';
        var pass = '';
        longueur = 5;
        for(i=0;i<longueur;i++){
            var wpos = Math.round(Math.random()*ok.length);
            pass+=ok.substring(wpos,wpos+1);
        }
        document.getElementById(champ_cible).value = pass;
    }
    /*
       <input name="password" id="password" type="text" />
       <input type="button" name="generer" value="Générer" onclick="javascript:generer_password('password');" />
     */
</script>


			
18 - [JavaScript] detect down/up scrolling - Le Hollandais Volant
// Initial state
var scrollPos = 0;
// adding scroll event
window.addEventListener('scroll', function(){ scrolling() });

// the function : compares the "new" scrolling state with the previous
// (this allows detecting either "up" or "down" scrolling)
// then saves the new in the $previous for the next iteration.

function scrolling() {
	if ((document.body.getBoundingClientRect()).top > scrollPos) {
		console.log('scrolling DOWN');
	} else {
		console.log('scrolling UP');
	}
	scrollPos = (document.body.getBoundingClientRect()).top;
}


			
19 - 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();}
	}
			
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 - 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();
		    }
		}
	}
			
24 - 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)));}


?>
			
25 - sendForm - poster un formulaire via ajax (sans lib)
	function sendForm(form){  
    	data='';
		url=form.getAttribute('action');
		Array.prototype.forEach.call(form.elements,function(obj){
			type=obj.getAttribute('type');
			if (
				type!='checkbox'&&type!='radio'&&type!='submit'
				||obj.checked==1
			){
				data+=obj.getAttribute('name')+'='+obj.value+'&';
			}
		});
    	
    	request = new XMLHttpRequest;
		request.open('post', url, true);
		request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		request.send(data);

		// Gestion de la réponse du serveur
		request.onreadystatechange=function(){
			if (request.readyState!=4 && request.status!=200){
				console.log(request.responseText);
			}
		}
	    return false;        
	}
			
28 - 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);
}
			
29 - 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));
	}
			
30 - 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;
    }
}
			
31 - Strip_cars
function strip_tags(input, allowed) {
				//http://phpjs.org/functions/strip_tags/
				allowed = (((allowed || '') + '')
				.toLowerCase()
				.match(/<[a-z][a-z0-9]*>/g) || [])
				.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
				var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
				commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
				return input.replace(commentsAndPhpTags, '')
				.replace(tags, function($0, $1) {
				  return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
				});
			}
			
33 - 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; } 
*/
			
34 - 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'));
			
35 - ScrollToTop sans jQuery - Ecyseo
/*
# ------------------ BEGIN LICENSE BLOCK ------------------
#
#
# Copyright (c) 2009 - 2014 Cyril MAGUIRE
# Licensed under the CeCILL v2.1 license.
# See http://www.cecill.info/licences.fr.html
#
# ------------------- END LICENSE BLOCK -------------------
*/
;(function(window,undefined) {

    'use_strict';

    var timeOut;
    var isIE = isIE();

    function isIE() {
        var nav = navigator.userAgent.toLowerCase();
        return (nav.indexOf('msie') != -1) ? parseInt(nav.split('msie')[1]) : false;
    }

    function backToTop() {
        if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
            window.scrollBy(0,-50);
            timeOut=setTimeout('backToTop()',40);
        }
        else {
            clearTimeout(timeOut);
        }
    }

    function getScrollPosition() {
        return Array((document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft,(document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop);
    }

    function Remove(idOfParent,idToRemove) {
        if (isIE) {
            document.getElementById(idToRemove).removeNode(true);
        } else {
            var Node1 = document.getElementById(idOfParent); 
            var len = Node1.childNodes.length;
            
            for(var i = 0; i < len; i++){           
                if (Node1.childNodes[i] != undefined && Node1.childNodes[i].id != undefined && Node1.childNodes[i].id == idToRemove){
                    Node1.removeChild(Node1.childNodes[i]);
                }
            }
        }   
    }

    function addElement(idOfParent,idToAdd,htmlToInsert) {
        var DomParent = document.getElementById(idOfParent);//id of body
        var newdiv = document.createElement('div');

        newdiv.setAttribute('id',idToAdd);
        newdiv.innerHTML = htmlToInsert;

        DomParent.appendChild(newdiv);
    }

    function displayBackButton() {
        var pos = [];
        var fleche = '\u21E7';

        if (isIE) {
            fleche = '\u25B2';
        }
        pos = getScrollPosition();
        var topLink = document.getElementById('toplink');
        if (pos[1] > 150) {
            if (topLink == null) {
                addElement('top','toplink',''+fleche+'');
            }
        } else {
            if (topLink != null) {
                Remove('top','toplink');
            }
        }
    }

    //add to global namespace
    window.onscroll = displayBackButton;
    window.displayBackButton = displayBackButton;
    window.backToTop = backToTop;


})(window);  
    

// CSS
#toplink {
    position: fixed;
    bottom: 20px;
    width: 100px;
    text-align: center;
    right:10px;
}
#toplink a { 
	font-size: 40px;
	opacity: 0.8;
}


			
36 - Connaitre la position du scroll dans la page

function getScrollPosition()
{
	return Array((document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft,(document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop);
}
			
37 - 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/‎',
		));
	}
			
38 - Demander confirmation de la fermeture d'un onglet
var confirmOnLeave = function(msg) {
 
    window.onbeforeunload = function (e) {
        e = e || window.event;
        msg = msg || '';
 
        // For IE and Firefox
        if (e) {e.returnValue = msg;}
 
        // For Chrome and Safari
        return msg;
    };
 
};
 
// message de confirmation générique du navigateur
confirmOnLeave();
 
// message de confirmation personnalisé
confirmOnLeave('Vous allez perdre votre travail, êtes vous sûr(e) de vouloir quitter la page ?');
			
39 - 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 - 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;
}
			
44 - 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);
}
			
45 - 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;
}

?>



			
46 - 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.'" ';     
}

			
47 - 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;  
}  
			
48 - 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!";}
			
50 - Slideshow minimaliste
/* CSS */
<style>
.fadein .carrousel .links{clear:both;width:100%;txtr}
.fadein { position:relative; width:100%; height:300px; } 
.fadein .carrousel { position:absolute; left:0; top:0; }

</style>
/* HTML */
<div class="fadein">
	<div class="carrousel car1">
		
		<div class="content">
			<h1>Titre du premier</h1>
			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
			tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
			quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
			consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
			cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupihref="" datat non
			proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

		</div>
		<div class="links">
			<em>1</em>
			<a href="" data="car2">2</a>
			<a href="" data="car3">3</a>
		</div>
	</div>
	<div class="carrousel car2">
		<div class="content">
			Ut enim ad minim veniam,
			quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
			consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
			cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupit non
			proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
		</div>
		<div class="links">
			
			<a href="" data="car1">1</a>
			<em>2</em>
			<a href="" data="car3">3</a>
		</div>
	</div>

	<div class="carrousel car3">
		<div class="content">
		</div>		
		<div class="links">			
			<a href="" data="car1">2</a>			
			<a href="" data="car2">3</a>
			<em>3</em>
		</div>
	</div>

</div>

/* JS/JQuery */
<script>
	$('.fadein .carrousel:gt(0)').hide();compteur=0;
	function slideshow(){
		z=setInterval(
			function(){
				compteur++;
				if (compteur==4){montre=1;cache=3;compteur=1;}
				else if (compteur>1){montre=compteur;cache=compteur-1;}
				else if (compteur==1){montre=1;cache=3;}
				
			  	$('.fadein > .car'+cache).fadeOut(500)
				.parent().find('.car'+montre).fadeIn(500)
				.end();
			}
		,5000);
		return z;
	}
	slide=slideshow();

        // si on survole, pause
	$('.fadein').hover(function(ev){
    	clearInterval(slide);
	}, function(ev){
		  slide = slideshow();
		}
	);
 
        // clic sur un lien pour changer de diapo
        $('.links a').click(function(){
        	car=$(this).attr('data');
        	$('.fadein > .carrousel').fadeOut(500)
		.parent().find('.car'+car).fadeIn(500)
		.end();
		compteur=car;
    	        return false;
        });

</script>
			
51 - 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'];
}
			
52 - 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;
}
			
53 - 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);
			
54 - 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);
}
			
55 - 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');
}
			
56 - 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);
}
			
57 - 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;
	}
}
			
58 - Fonctions récupérées de regexpal (à creuser)
/*
	Helper functions for RegexPal
	(c) 2007 Steven Levithan <http://stevenlevithan.com>
	MIT license
*/

function $ (el) {
	if (el.nodeName) return el;
	if (typeof el === "string") return document.getElementById(el);
	return false;
};

var trim = function () {
	// See <http://blog.stevenlevithan.com/archives/faster-trim-javascript>
	var	lSpace = /^ss*/,
		rSpace = /ss*$/;
	return function (str) {
		return str.replace(lSpace, "").replace(rSpace, "");
	};
}();

// This is much faster than simple use of innerHTML in some browsers
// See <http://blog.stevenlevithan.com/archives/faster-than-innerhtml>
function replaceHtml (el, html) {
	var oldEl = $(el);
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

/* outerHTML is used to work around the fact that IE applies text normalization when using innerHTML,
which can cause problems with whitespace, etc. Note that even this approach doesn't work with some
elements such as <div>. However, it mostly works with <pre> elements, at least. */
function replaceOuterHtml (el, html) {
	el = replaceHtml(el, "");
	if (el.outerHTML) { // If IE
		var	id = el.id,
			className = el.className,
			nodeName = el.nodeName;
		el.outerHTML = "<" + nodeName + " id="" + id + "" class="" + className + "">" + html + "</" + nodeName + ">";
		el = $(id); // Reassign, since we just overwrote the element in the DOM
	} else {
		el.innerHTML = html;
	}
	return el;
};

// Return an array of all elements with a specified class name, optionally filtered by tag name and parent
function getElementsByClassName (className, tagName, parentNode) {
	var	els = ($(parentNode) || document).getElementsByTagName(tagName || "*"),
		results = [];
	for (var i = 0; i < els.length; i++) {
		if (hasClass(className, els[i])) results.push(els[i]);
	}
	return results;
};

function hasClass (className, el) {
	/* It might not make sense to cache all regexes in a more widely used hasClass function,
	but RegexPal uses it with a small number of classes so there is little memory overhead. */
	return XRegExp.cache("(?:^|s)" + className + "(?:s|$)").test($(el).className);
};

function addClass (className, el) {
	el = $(el);
	if (!hasClass(className, el)) {
		el.className = trim(el.className + " " + className);
	}
};

function removeClass (className, el) {
	el = $(el);
	el.className = trim(el.className.replace(XRegExp.cache("(?:^|s)" + className + "(?:s|$)", "g"), " "));
};

function toggleClass (className, el) {
	if (hasClass(className, el)) {
		removeClass(className, el);
	} else {
		addClass(className, el);
	}
};

function swapClass (oldClass, newClass, el) {
	removeClass(oldClass, el);
	addClass(newClass, el);
};

function replaceSelection (textbox, str) {
	if (textbox.setSelectionRange) {
		var	start = textbox.selectionStart,
			end = textbox.selectionEnd,
			offset = (start + str.length);
		textbox.value = (textbox.value.substring(0, start) + str + textbox.value.substring(end));
		textbox.setSelectionRange(offset, offset);
	} else if (document.selection) { // If IE (Opera has setSelectionRange and Selection objects)
		var range = document.selection.createRange();
		range.text = str;
		range.select();
	}
};

function extend (to, from) {
	for (var property in from) to[property] = from[property];
	return to;
};

// purge by Douglas Crockford <http://javascript.crockford.com/memory/leak.html>
function purge (d) {
	var a = d.attributes, i, l, n;
	if (a) {
		l = a.length;
		for (i = 0; i < l; i += 1) {
			n = a[i].name;
			if (typeof d[n] === 'function') {
				d[n] = null;
			}
		}
	}
	a = d.childNodes;
	if (a) {
		l = a.length;
		for (i = 0; i < l; i += 1) {
			purge(d.childNodes[i]);
		}
	}
};

// Sniff
var	isWebKit = navigator.userAgent.indexOf("WebKit") > -1,
	isIE /*@cc_on = true @*/,
	isIE6 = isIE && !window.XMLHttpRequest; // Despite the variable name, this means if IE lower than v7

// RegexPal also needs an Array.prototype.indexOf method, but it's provided by XRegExp

			
59 - 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();}}

			
62 - 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;
}
			
63 - 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'));

?> 
			
64 - 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 />';
}
?>
			
65 - 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);
}


			
66 - 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');
#################################################################
?>
			
67 - 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;  
}  
			
68 - 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 />';  
}  
			
71 - 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";  
    }  
}  
			
72 - 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);  
			
73 - 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" />';  
}  
			
74 - 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, ' ');
			
75 - 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);  
			
76 - 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;  
} 
			
77 - 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;
			
78 - 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);
?>
			
79 - 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;
}
			
80 - 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);
}
			
81 - 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');
			
82 - 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';
}
			
83 - 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');