PHP

De bricosoft
Aller à la navigation Aller à la recherche
Fichier:Borat Great Success.jpg
ah wa wa waa, grand succèèès, PHP langage numéro un dans tout Kazakhstan
<google uid="C08" position="left"></google>

PHP est l'acronyme de problème d'hygiène personnelle.

Fichier:Php logo.png
echo "Le logo de PHP.";
  • "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." 0x58

$_SERVER['SERVER_NAME'] vs $_SERVER['HTTP_HOST']

  • $_SERVER['HTTP_HOST']
    • dépend de la requête HTTP par le client(navigateur). Prends le contenu de l'entête Host: s'il existe.

Conclusion : ne pas faire une confiance aveugle aux valeurs du tableau $_SERVER sauf si l'on maîtrise la configuration du serveur web (UseCanonicalName On + ServerName www.bricosoft.com pour Apache) et on prendra SERVER_NAME.

foreach par reference

<source lang="php">

foreach ($arr as &$value) {
   $value = $value * 2;
}

</source>

Afficher une image aléatoirement / randomized printed image

Ce petit programme renvoie une image parmi les images présentes dans le dossier.

http://tremulous.bricosoft.com/images/banniere/b.php

Les images dans le dossier (jpg ou png) : http://tremulous.bricosoft.com/images/banniere/

Le source : http://tremulous.bricosoft.com/images/banniere/b.phps


Utilité : avatar aléatoire, égayer une page...

Eclipse

http://www.eclipse.org/php

Help>Software Updates>Find and Install
*Search for new features to install
**New Remote Site
***Name: PDT URL: http://download.eclipse.org/tools/pdt/updates/
Finish

Selectionnez Callisto et PDT, en cas de plugins manquant, mettez en surbrillance Callisto puis cliquez sur "Select Required", les paquets manquants seront sélectionnés automatiquement.

Détecter IE <= 6

<source lang="php">

if( preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT']) ) 
  // IE <= 6
else
  // autre

</source>

Unicode vers Html

Erreur dans le widget Twitter Search: unable to write file /home/gbp4dt5/zones/bricosoft.com/www/extensions/Widgets/compiled_templates/wrt69389f13b45031_77123728

Par exemple ä est unicodé en "U+00E4" : <source lang="php">

$ php -r "echo base_convert('00E4',16,10);"
228

</source> L'entité html est donc :

ä

Preuve : <source lang="php">

html_entity_decode('&#'.base_convert('00E4',16,10).';',ENT_QUOTES, 'UTF-8');"
$ php -r "echo html_entity_decode('&#'.base_convert('00E4',16,10).';',ENT_QUOTES, 'UTF-8');"
ä

</source>

En CLI (le fichier doit être encodé en UTF-8) : <source lang="php">

  1. !/usr/bin/php -q

<?php //php -r "echo html_entity_decode('&#'.base_convert('00E4',16,10).';',ENT_QUOTES, 'UTF-8');"

$sT= 'á, à, ă, â, å, ä, ã, ą, ā, æ, ć, ĉ, č, ċ, ç, ď, đ, é, è, ĕ, ê, ě, ë, ė, ę, ē, ğ, ĝ, ġ, ģ, ĥ, ħ, í, ì, ĭ, î, ï, ĩ, į, ī, ı, ĵ, ķ, ĸ, ĺ, ľ, ļ, ł, ń, ň, ñ, ņ, ŋ, ó, ò, ŏ, ô, ö, ő, õ, ø, ō, ŕ, ř, ŗ, ś, ŝ, ş, ť, ţ, ŧ, ú, ù, ŭ, û, ů, ü, ű, ũ, ų, ū, ŵ, ý, ŷ, ÿ, ź, ż, ð, þ, á, é, í, ñ, ó';

$aU= explode(',',$sT); $aU= array_map('trim', $aU); $aH= array(); foreach ($aU as $sC) { if ( !ereg('#', $sC) ) { $aH[]= htmlentities($sC, ENT_NOQUOTES, 'UTF-8'); } else { $aH[]= $sC; } } print_r( $aU ); $aH= array_unique($aH); print_r( implode(',',$aH) ); ?> </source> Affichera : <source lang="html4strict"> á,à,ă,â,å,ä,ã,ą,ā,æ,ć,ĉ,č,ċ,ç,ď,đ,é,è,ĕ,ê,ě,ë,ė,ę,ē,ğ,ĝ,ġ,ģ,ĥ,ħ,í,ì,ĭ,î,ï,ĩ,į,ī,ı,ĵ,ķ,ĸ,ĺ,ľ,ļ,ł,ń,ň,ñ,ņ,ŋ,ó,ò,ŏ,ô,ö,ő,õ,ø,ō,ŕ,ř,ŗ,ś,ŝ,ş,ť,ţ,ŧ,ú,ù,ŭ,û,ů,ü,ű,ũ,ų,ū,ŵ,ý,ŷ,ÿ,ź,ż,ð,þ </source>

string to array

<google uid="C08" position="right"></google>

<source lang="php"> $sUtf= 'éééé'; // string UTF-8 $iSize= strlen($sUtf); for($i=0; $i < $iSize; $i++) {

 	$aChars[$i]=	$sUtf[$i];

} </source>

$aChars outputs:

Array
        (
            [0] => �
            [1] => �
            [2] => �
            [3] => �
            [4] => �
            [5] => �
            [6] => �
            [7] => �
        )

:-(

<source lang="php"> $sUtf= 'éééé'; // string UTF-8 $iSize= mb_strlen($sUtf, 'UTF-8'); for($i=0; $i < $iSize; $i++) { $char = mb_substr ($sUtf, $i, 1, 'UTF-8');

      	$aChars[$i]=	$char;

} </source> $aChars outputs:

Array
       (
            [0] => é
            [1] => é
            [2] => é
            [3] => é
       )

:-)

Cache APC

Fichier:Yezhik.jpg
Kro meugnon!!!<3<3<3
Fichier:Giant Panda Eating.jpg
Kro meugnon!!!<3<3<3

cf APC.

debug_backtrace()

debug_backtrace() est bien utile :))

récupérer les paramêtres d'une méthodes sans paramêtres

Utile en refactoring, sans changer la signature d'une méthode on peut récupérer des paramètres en plus avec func_get_args()

Avant : <source lang="php"> class Panda extends Ursidae {

   function Panda($aInit= null)
   {
   	if(!empty($aInit)) {

foreach ($aInit as $k => $v) { if (!empty($v)) { $this->$k= $v; } }

   	}
   }

} </source>

Après (on peut garder la signature obsolète) : <source lang="php"> class Panda extends Ursidae {

   function Panda()
   {
   	$args = func_get_args();
       if (is_array($args)) {
   		$args= $args[0];
   	}   
       foreach ($args as $k => $v) {  

if (!empty($v)) { $this->$k= $v; } }

   }

}


$oPanda= new Panda('poids'= 110); </source>

implode de tableau associatif, array to string

$ php -a
Interactive shell

php > $aTrucs= array('fruit'=>'pomme','outil'=>'cle a molette','alibi'=>'traineau');

php > echo http_build_query($aTrucs,'', ' ');
fruit=pomme outil=cle+a+molette alibi=traineau

php > http_build_query rulez

No need to s'emmerder.


Google referer key word / mot clés d'un visiteur provenant de google

On détricote l'url de recherche qu'un visiteur génère lorsqu'il arrive sur votre site via google. Par contre depuis la généralisation d'https pour les gars connecté vous n'auriez rien, nada, ralouf.

<source lang="php"> // le referer $sReferer = strtolower($_SERVER['HTTP_REFERER']); // on verifie si ca vient de google if ( strpos($sReferer,"google") ) { // on efface tout ce qu'il y a avant q= la variable qui contient la chaine de recherche

       $sApresLeQ= substr($sReferer, strpos($sReferer,"q="));		

// on enleve q= $sChaineRecherche= substr($sApresLeQ,2); // efface les parametres inutiles, cad tout apres le prochain eperluette & if (strpos($sChaineRecherche,"&")) { $sChaineRecherche= substr($sChaineRecherche, 0,strpos($sChaineRecherche,"&")); } // et voila. $sMotsClesGoogle= urldecode($sChaineRecherche); } </source>

Les méthodes magiques

PHP et les méthodes magiques >>> Java.

Pour faciliter votre compréhension (et pourquoi pas ?) les exemples seront avec cet objet : <source lang="php"> class Poulpe extends Octopus { public $iDureeVieMax= 2; /* annees */

function Poulpe() { } } </source> Qui n'est autre qu'un poulpe très simple ou octopus vulgaris simplex en pseudo taxonomie de troquet.

__get()

__set()

__call()

__callStatic()

__construct()

__destruct()

__toString()

__set_state()

__clone()

__sleep()

__wakeup()

__autoload()

__invoke()

preg_quote

Cette fonction échappe les motifs de regexp :

$sDtc= "ou.";
if ( preg_match("/".preg_quote($sDtc)."/", $sPhrase) {
  echo "DTC !!!";
}

PHP bashing

true is false

$ php -a
Interactive shell
php > if ((true == "foo") && ("foo" == 0) && (0 == false)) echo "lawl";
lawl

héxa

In PHP, echo 0x0 +2; returns 4, but echo 0x0+ 2; returns 2.

LOL, try it on your command line: php -r 'echo 0x0+ 2;' vs php -r 'echo 0x0 +2;'

source : [1]

Voir aussi

Liens