1 - trier des fichiers par date (ascendant)
$files=glob('*');
usort(
$files,
function($file1, $file2) {
return filemtime($file1) <=> filemtime($file2);
}
);
// pour descendant:
$files=array_reverse($files);
$files=glob('*');
usort(
$files,
function($file1, $file2) {
return filemtime($file1) <=> filemtime($file2);
}
);
// pour descendant:
$files=array_reverse($files);
def locale_load(self,lang):
locale_file='sys/locales/'+lang+".locale"
if not os.path.isfile(locale_file):
self.locale={}
return
locale={}
locale_str=file_get_contents(locale_file)
locale_str=re.findall('\"(?P<eng>.*?)\"=\"(?P<trad>.*?)\"',locale_str)
for key,val in enumerate(locale_str):
locale[locale_str[key][0]]=locale_str[key][1]
self.locale=locale
# syntaxe du fichier locale
#"Title"="Titre",
#"Author"="Auteur",
#"Language"="Langue",
def trad(self,term):
if not term in self.locale:
return term
return self.locale[term]
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/"
import urllib
# get_distant_file function
def get_distant_file(string):
try:
data=urllib.urlopen(string).read()
except:
data=""
finally:
return data.encode('utf8')
# file_get_contents function
def file_get_contents(filename):
content=""
if not os.path.isfile(filename): return false
f = open(filename, 'r')
try:
content=f.read(1000000).decode('utf8')
finally:
f.close()
return content
# file_put_contents function
def file_put_contents(filename,data):
if not os.path.isfile(filename): return false
f = open(filename, 'w')
f.write(data.decode('utf8'))
f.close()
# saveJson function
def saveJson(filename,data):
f = open(filename, 'w')
f.write(json.dumps(data))
f.close()
# loadJson function
def loadJson(filename):
if not os.path.isfile(filename): return false
f = open(filename, 'r')
content=f.read()
if content=="":return {}
return json.loads(content)
// 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;
}
# 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)))));
}
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();
}
}
}
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;
}
<?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)));}
?>
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
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));
}
/**
* 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;
}
}
function only_alphanum_and_dot($string){return preg_replace('#[^a-zA-Z0-9\. ]#','',$string);}
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/',
));
}
$extension=pathinfo($dir,PATHINFO_EXTENSION);
<?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));
?>
// 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>';
}
// 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!";}
$(function(){
$("select#ctlJob").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#ctlPerson").html(options);
})
})
})
var loading = false;
$(window).scroll(function(){
if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
if(loading == false){
loading = true;
$('#loadingbar').css("display","block");
$.get("load.php?start="+$('#loaded_max').val(), function(loaded){
$('body').append(loaded);
$('#loaded_max').val(parseInt($('#loaded_max').val())+50);
$('#loadingbar').css("display","none");
loading = false;
});
}
}
});
$(document).ready(function() {
$('#loaded_max').val(50);
});
# 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;
}
#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... }
/********************
*@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";
}
}
/* 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);
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';
}
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');