Yosko's snippets

Snippets gathered around the web



CSS 2 CSharp 1 HTML 2 Javascript 2 PHP 12 XML 1 color 2 image 1 security 2

.

PHP

Afficher toutes les erreurs en PHP directement dans le navigateur

error_reporting(E_ALL);
ini_set('display_errors', 'On');

PHP

<iframe width="100%" height="218" src="http://snip.yosko.net/index.php?embed=5eda68b24f098" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 05/06/2020

Base64 image in HTML/PHP

<?php

// GD method
ob_start ();
$img = imagecreatefrompng('source.png');
imagepng($img);
$img_data = ob_get_contents ();
ob_end_clean ();

// file method
$img_data = file_gets_contents('source.png');

// encode data in base64
$img_data_base64 = base64_encode ($img_data);

?>

<img src="data:image/png;base64,<?php echo $img_data_base64; ?>" alt="">

HTML PHP

<iframe width="100%" height="506" src="http://snip.yosko.net/index.php?embed=564065d96ea1d" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 09/11/2015

Intégrez une "base de données" dans votre fichier unique d’exécution

<?php

//On ouvre la base de donnée sous forme de tableau
$db = db();
//on ajoute quelques données et on affiche la base
@$db['entries'][] = 'hello world '.count(@$db['entries']);
var_dump($db);
//on enregistre la base
db($db);

//A partir d'ici, ne touchez à rien ou tout explose.

//Base de donnée json compressée
$database = '';
//fonction de gestion de base de donnée intégrée
function db($d=false){
    $s = file_get_contents(__FILE__);
    if(!$d){
        preg_match_all('/\$database = \'(.*?)\';/s', $s, $result, PREG_PATTERN_ORDER);
        return $result[1][0]==''?array():json_decode(gzinflate($result[1][0]),true);
    }else{
        file_put_contents(__FILE__,preg_replace('/\$database = \'(.*?)\';/s', '$database = \''.gzdeflate(json_encode($d)).'\';', $s));
    }
}
?>    

PHP

http://blog.idleman.fr/snippet-25-php-integrez-une-base-de-donnee-dans-votre-fichier-unique-dexecution/

<iframe width="100%" height="632" src="http://snip.yosko.net/index.php?embed=538ebf4d50728" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 04/06/2014

Dom2Array + Array2Dom

<?php
 
/**
* Recursive function to turn a DOMDocument element to an array
* @param DOMDocument $root the document (might also be a DOMElement/DOMNode?)
*/
function Dom2Array($root) {
    $array = array();
     
    if($root->hasAttributes()) {
        foreach($root->attributes as $attribute) {
            $array['_attributes'][$attribute->name] = $attribute->value;
        }
    }
    if($root->hasChildNodes()) {
        $children = $root->childNodes;
        if($children->length == 1
            && ($children->item(0)->nodeType == XML_TEXT_NODE
            || $children->item(0)->nodeType == XML_CDATA_SECTION_NODE)
        ) {
            $array['_value'] = $children->item(0)->nodeValue;
        } else {
            for($i = 0; $i < $children->length; $i++) {
                if($children->item($i)->nodeType == XML_ELEMENT_NODE) {
                    $child = $children->item($i);
                    $array['_children'][$child->nodeName] = Dom2Array($child);
                }
            }
        }
    }
    return $array;
}
 
/**
* Recursive function to turn an array to a DOMDocument
* @param array $array the array
* @param string $name only used by recursion
* @param DOMDocument $doc only used by recursion
*/
function Array2Dom($array, $name = '', $doc = null) {
    //current node
    if($doc == null) {
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $currentNode = $doc;
    } else {
        $currentNode = $doc->createElement($name);
    }
     
    //children/attributes/values of current node
    foreach($array as $key => $value) {
        if($key == '_value') {
            $currentNode->nodeValue = $value;
        } elseif($key == '_attributes') {
            foreach($value as $name => $attribute) {
                $currentNode->setAttribute($name, $attribute);
            }
        } elseif($key == '_children') {
            foreach($value as $name => $child) {
                $childNode = Array2Dom($child, $name, $doc);
                $childNode = $currentNode->appendChild($childNode);
            }
        }
    }
     
    return $currentNode;
}
 
?>

PHP XML

https://gist.github.com/yosko/6991691

<iframe width="100%" height="1424" src="http://snip.yosko.net/index.php?embed=525d460027f5b" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 12/05/2015

search2feed : transformer une recherche en flux

<?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("xefxbbxbfxA0", '',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));

?>

PHP

http://www.warriordudimanche.net/article193/search2feed-transformer-une-recherche-en-flux

<iframe width="100%" height="3044" src="http://snip.yosko.net/index.php?embed=52550a9ce8577" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 09/10/2013

Trouver jours fériés (fixes et mouvants)

?php    
/**
    * Cette fonction retourne un tableau de timestamp correspondant
    * aux jours fériés en France pour une année donnée.
    */
    function isNotWorkable($date)
    {

          if ($date === null)
          {
            $date = time();
          }

         $date = strtotime(date('m/d/Y',$date));

         $year = date('Y',$date);

        $easterDate  = easter_date($year);
        $easterDay   = date('j', $easterDate);
        $easterMonth = date('n', $easterDate);
        $easterYear   = date('Y', $easterDate);

        $holidays = array(
        // Dates fixes
        mktime(0, 0, 0, 1,  1,  $year),  // 1er janvier
        mktime(0, 0, 0, 5,  1,  $year),  // Fête du travail
        mktime(0, 0, 0, 5,  8,  $year),  // Victoire des alliés
        mktime(0, 0, 0, 7,  14, $year),  // Fête nationale
        mktime(0, 0, 0, 8,  15, $year),  // Assomption
        mktime(0, 0, 0, 11, 1,  $year),  // Toussaint
        mktime(0, 0, 0, 11, 11, $year),  // Armistice
        mktime(0, 0, 0, 12, 25, $year),  // Noel

        // Dates variables
        mktime(0, 0, 0, $easterMonth, $easterDay + 1,  $easterYear),
        mktime(0, 0, 0, $easterMonth, $easterDay + 39, $easterYear),
        mktime(0, 0, 0, $easterMonth, $easterDay + 50, $easterYear),
        );

      return in_array($date, $holidays);
    }
?>

PHP

http://blog.idleman.fr/snippet-23-php-trouver-les-jours-feries-fixes-et-mouvants/#comment-31709

<iframe width="100%" height="938" src="http://snip.yosko.net/index.php?embed=5236b38a00a72" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 16/09/2013

Array2feed: produire un flux valide à partir d'un tableau

# 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);

PHP

http://www.warriordudimanche.net/article179/array2feed-produire-un-flux-valide-a-partir-d-un-tableau

<iframe width="100%" height="2018" src="http://snip.yosko.net/index.php?embed=5204f5bf0876f" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 09/08/2013

Color conversion

/*
    Color lib by Yosko (http://www.yosko.net/)
    Licence: WTFPL except for the following
    source for HSL algorithm: http://www.easyrgb.com/index.php?X=MATH
*/

//returns a clean 6 digit hex number as a string
function cleanHexColor($hex) {
    $hex = strtolower($hex);
    //remove the leading "#"
    if(strlen($hex) == 7 || strlen($hex) == 4)
        $hex = substr($hex, -(strlen($hex)-1));
    
    // $hex like "1a7"
    if(preg_match('/^[a-f0-9]{6}$/i', $hex))
        return $hex;
    // $hex like "162a7b"
    elseif(preg_match('/^[a-f0-9]{3}$/i', $hex))
        return $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    //any other format
    else
        return "000000";
}

//returns an array of 3 [0-255] int
function hex2rgb($hex) {
    return array(
        hexdec(substr($hex, 0, 2)),
        hexdec(substr($hex, 2, 2)),
        hexdec(substr($hex, 4, 2)),
    );
}

//returns a 6 digit hex number as a string
function rgb2hex($rgb) {
    return ""
        .substr("00".dechex(ceil($rgb[0])), -2)
        .substr("00".dechex(ceil($rgb[1])), -2)
        .substr("00".dechex(ceil($rgb[2])), -2)
    ;
}

//returns a 2 dimensional array of subarrays (HSL: 3 values [0-1] floats)
function variationAround($hsl, $stepSize = 0.2,  $constant = "hue") {
    if($constant == "hue") {
        $i = 1; $j = 2;
    } elseif($constant == "sat") {
        $i = 0; $j = 2;
    }if($constant == "lum") {
        $i = 0; $j = 1;
    }
    
    $variations = array();  //resulting variations
    $hslTemp = array();     //stores current variation
    $mod = array();         //stores modulos for h, s & l
    
    $mod[0] = (float)(($hsl[0]*100) % ($stepSize * 100)) / 100;
    $mod[1] = (float)(($hsl[1]*100) % ($stepSize * 100)) / 100;
    $mod[2] = (float)(($hsl[2]*100) % ($stepSize * 100)) / 100;
    
    $hslTemp = $hsl;
    $hslTemp[$i] = $mod[$i];
    while($hslTemp[$i] <= 1) {
        $row = array();
        $hslTemp[$j] = $mod[$j];
        while($hslTemp[$j] <= 1) {
            $row[(string)$hslTemp[$j]] = array($hslTemp[0], $hslTemp[1], $hslTemp[2]);
            $hslTemp[$j] = (float)($hslTemp[$j] + $stepSize);
        }
        $variations[(string)$hslTemp[$i]] = $row;
        $hslTemp[$i] = (float)($hslTemp[$i] + $stepSize);
    }
    
    return $variations;
}

function rgb2hsl($rgb) {
    //work with range [0-1] for RGB values
    $r = $rgb[0] / 255;
    $g = $rgb[1] / 255;
    $b = $rgb[2] / 255;
    
    //get min and max from RGB
    $min = min($r, $g, $b);
    $max = max($r, $g, $b);
    $delta = $max-$min;
    
    //luminance
    $l = ($max + $min) / 2;
    
    //saturation & hue
    if($min == $max) {
        //grayscale
        $s = 0;
        $h = 0;
    } else {
        //saturation
        if($l < 0.5)    $s = $delta/($max+$min);
        else            $s = $delta/(2-$max-$min);
        
        //hue
        if($r == $max)      $h = ($g-$b)/(6*$delta);
        elseif($g == $max)  $h = 1/3 + ($b-$r)/(6*$delta);
        elseif($b == $max)  $h = 2/3 + ($r-$g)/(6*$delta);
        
        //keep hue in the range [0,1]
        if ($h < 0) $h++;
        if ($h > 1) $h--;
    }
    
    return array($h, $s, $l);
}

function hsl2rgb($hsl) {
    $h = $hsl[0];
    $s = $hsl[1];
    $l = $hsl[2];
    
    //no saturation: grayscale
    if($s == 0) {
        $r = $g = $b = round($l * 255);
    } else {
        if($l < 0.5)    $var2 = $l * (1 + $s);
        else            $var2 = ($l + $s) - ($s * $l);
        
        $var1 = 2 * $l - $var2;
        
        $r = 255 * hue2rgb($var1, $var2, $h + 1/3);
        $g = 255 * hue2rgb($var1, $var2, $h);
        $b = 255 * hue2rgb($var1, $var2, $h - 1/3);
    }
    
    return array($r, $g, $b);
}

function hue2rgb($v1, $v2, $vH)
{
   if ( $vH < 0 ) $vH += 1;
   if ( $vH > 1 ) $vH -= 1;
   if ( $vH < 1/6 ) return $v1 + ( $v2 - $v1 ) * 6 * $vH;
   elseif ( $vH < 1/2 ) return $v2;
   elseif ( $vH < 2/3 ) return $v1 + ( $v2 - $v1 ) * ( 2/3 - $vH ) * 6;
   else return ( $v1 );
}

PHP color

<iframe width="100%" height="2774" src="http://snip.yosko.net/index.php?embed=5200a8226193a" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 06/08/2013

Afficher toutes les erreurs

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors','On');
ini_set('log_errors', 'On');
ini_set('error_log', 'errors.log');

PHP

<iframe width="100%" height="254" src="http://snip.yosko.net/index.php?embed=5200a8057ab91" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 14/02/2014

Afficher flux image en base64

// A few settings
$image = 'cricci.jpg';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="',$src,'">';

image PHP

<iframe width="100%" height="380" src="http://snip.yosko.net/index.php?embed=5200a7eac4b2a" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 06/08/2013

Récupérer adresse IP même derrière un proxy

/**
 * get client IP from the best source possible (even through a server proxy)
 * based on: http://stackoverflow.com/questions/1634782/what-is-the-most-accurate-way-to-retrieve-a-users-correct-ip-address-in-php
 * @return string ip address (ipv4 or ipv6)
 */
public static function getIpAddress($local=false) {
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe
                if ($local === true && filter_var($ip, FILTER_VALIDATE_IP) !== false
                    || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false
                ){
                    return $ip;
                }
            }
        }
    }
}

security PHP

http://stackoverflow.com/questions/1634782/what-is-the-most-accurate-way-to-retrieve-a-users-correct-ip-address-in-php

<iframe width="100%" height="524" src="http://snip.yosko.net/index.php?embed=5200a7c96c133" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 06/08/2013

Brute force protection system (sebsauvage)

<?php

date_default_timezone_set('Europe/Paris');
$GLOBALS['config']['DATADIR'] = 'data'; // Data subdirectory
$GLOBALS['config']['IPBANS_FILENAME'] = $GLOBALS['config']['DATADIR'].'/ipbans.php'; // File storage for failures and bans.
$GLOBALS['config']['BAN_AFTER'] = 5; // Ban IP after this many failures.
$GLOBALS['config']['BAN_DURATION'] = 1800; // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
if (!is_dir($GLOBALS['config']['DATADIR'])) { mkdir($GLOBALS['config']['DATADIR'],0705); chmod($GLOBALS['config']['DATADIR'],0705); }
if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from nonenDeny from alln"); } // Protect data files.

function logm($message)
{
    $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."n";
    file_put_contents($GLOBALS['config']['DATADIR'].'/log.txt',$t,FILE_APPEND);
}


// ------------------------------------------------------------------------------------------
// Brute force protection system
// Several consecutive failed logins will ban the IP address for 30 minutes.
if (!is_file($GLOBALS['config']['IPBANS_FILENAME'])) file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?phpn$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";n?>");
include $GLOBALS['config']['IPBANS_FILENAME'];
// Signal a failed login. Will ban the IP if too many failures:
function ban_loginFailed()
{
    $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
    if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
    $gb['FAILURES'][$ip]++;
    if ($gb['FAILURES'][$ip]>($GLOBALS['config']['BAN_AFTER']-1))
    {
        $gb['BANS'][$ip]=time()+$GLOBALS['config']['BAN_DURATION'];
        logm('IP address banned from login');
    }
    $GLOBALS['IPBANS'] = $gb;
    file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?phpn$GLOBALS['IPBANS']=".var_export($gb,true).";n?>");
}

// Signals a successful login. Resets failed login counter.
function ban_loginOk()
{
    $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
    unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
    $GLOBALS['IPBANS'] = $gb;
    file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?phpn$GLOBALS['IPBANS']=".var_export($gb,true).";n?>");
    logm('Login ok.');
}

// Checks if the user CAN login. If 'true', the user can try to login.
function ban_canLogin()
{
    $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
    if (isset($gb['BANS'][$ip]))
    {
        // User is banned. Check if the ban has expired:
        if ($gb['BANS'][$ip]<=time())
        { // Ban expired, user can try to login again.
            logm('Ban lifted.');
            unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
            file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?phpn$GLOBALS['IPBANS']=".var_export($gb,true).";n?>");
            return true; // Ban has expired, user can login.
        }
        return false; // User is banned.
    }
    return true; // User is not banned.
}

?>

PHP security

http://sebsauvage.net/links/?kO4Krg

<iframe width="100%" height="1388" src="http://snip.yosko.net/index.php?embed=5200a56022581" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 06/08/2013

This page's Feed


Yosko's snippets 1.84 by Bronco - generated in 0.008 s