« PHP » : différence entre les versions

De bricosoft
 
m Remplacement des balises <source> obsolètes par <syntaxhighlight> (bot)
 
(Une version intermédiaire par un autre utilisateur non affichée)
Ligne 1 : Ligne 1 :
[[image:Borat_Great_Success.jpg|thumb|ah wa wa waa, grand succèèès, PHP langage numéro un dans tout Kazakhstan]]
[[image:Borat_Great_Success.jpg|thumb|ah wa wa waa, grand succèèès, PHP langage numéro un dans tout Kazakhstan]]
<div class="thumb tright"><google uid="C08" position="left"></google></div>
'''PHP''' est l'acronyme de problème d'hygiène personnelle.
'''PHP''' est l'acronyme de problème d'hygiène personnelle.
[[Image:Php logo.png|frame|echo "Le logo de PHP.";]]
[[Image:Php logo.png|frame|echo "Le logo de PHP.";]]
Ligne 15 : Ligne 14 :


== foreach par reference ==
== foreach par reference ==
<source lang="php">
<syntaxhighlight lang="php">
  foreach ($arr as &$value) {
  foreach ($arr as &$value) {
     $value = $value * 2;
     $value = $value * 2;
  }
  }
</source>
</syntaxhighlight>


==Afficher une image aléatoirement / randomized printed image==
==Afficher une image aléatoirement / randomized printed image==
Ligne 33 : Ligne 32 :


{{boîte déroulante|align=left|alignT=center|titre=code source|contenu=
{{boîte déroulante|align=left|alignT=center|titre=code source|contenu=
<source lang="c">
<syntaxhighlight lang="c">
$files  = array();    // Contient la liste des images
$files  = array();    // Contient la liste des images
$filesn = array('.', '..', '.htaccess', 'b.php'); // Fichiers qu'on ne doit pas prendre en compte dans la liste
$filesn = array('.', '..', '.htaccess', 'b.php'); // Fichiers qu'on ne doit pas prendre en compte dans la liste
Ligne 66 : Ligne 65 :
imagejpeg($image);
imagejpeg($image);
}
}
</source>
</syntaxhighlight>
}}
}}


Ligne 81 : Ligne 80 :


==Détecter IE <= 6==
==Détecter IE <= 6==
<source lang="php">
<syntaxhighlight lang="php">
  if( preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT']) )  
  if( preg_match('/(?i)msie [1-6]/',$_SERVER['HTTP_USER_AGENT']) )  
   // IE <= 6
   // IE <= 6
  else
  else
   // autre
   // autre
</source>
</syntaxhighlight>


==Unicode vers Html==
==Unicode vers Html==
<div class="thumb tright">{{#widget:Twitter Search
|query=#{{PAGENAME}}
|title=Bricosoft.com/{{PAGENAME}}
|caption=Ce que les gens disent sur {{PAGENAME}}
}}
</div>
Par exemple ä est unicodé en "U+00E4" :
Par exemple ä est unicodé en "U+00E4" :
<source lang="php">
<syntaxhighlight lang="php">
  $ php -r "echo base_convert('00E4',16,10);"
  $ php -r "echo base_convert('00E4',16,10);"
  228
  228
</source>
</syntaxhighlight>
L'entité html est donc :
L'entité html est donc :
  &#228;
  &#228;


Preuve :
Preuve :
<source lang="php">
<syntaxhighlight lang="php">
  html_entity_decode('&#'.base_convert('00E4',16,10).';',ENT_QUOTES, 'UTF-8');"
  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');"
  $ php -r "echo html_entity_decode('&#'.base_convert('00E4',16,10).';',ENT_QUOTES, 'UTF-8');"
  ä
  ä
</source>
</syntaxhighlight>


En CLI (le fichier doit être encodé en UTF-8) :
En CLI (le fichier doit être encodé en UTF-8) :
<source lang="php">
<syntaxhighlight lang="php">
#!/usr/bin/php -q
#!/usr/bin/php -q
<?php
<?php
Ligne 145 : Ligne 138 :
print_r( implode(',',$aH) );
print_r( implode(',',$aH) );
?>
?>
</source>
</syntaxhighlight>
Affichera :
Affichera :
<source lang="html4strict">
<syntaxhighlight lang="html4strict">
&aacute;,&agrave;,&#259;,&acirc;,&aring;,&auml;,&atilde;,&#261;,&#257;,&aelig;,&#263;,&#265;,&#269;,&#267;,&ccedil;,&#271;,&#273;,&eacute;,&egrave;,&#277;,&ecirc;,&#283;,&euml;,&#279;,&#281;,&#275;,&#287;,&#285;,&#289;,&#291;,&#293;,&#295;,&iacute;,&igrave;,&#301;,&icirc;,&iuml;,&#297;,&#303;,&#299;,&#305;,&#309;,&#311;,&#312;,&#314;,&#318;,&#316;,&#322;,&#324;,&#328;,&ntilde;,&#326;,&#331;,&oacute;,&ograve;,&#335;,&ocirc;,&ouml;,&#337;,&otilde;,&oslash;,&#333;,&#341;,&#345;,&#343;,&#347;,&#349;,&#351;,&#357;,&#355;,&#359;,&uacute;,&ugrave;,&#365;,&ucirc;,&#367;,&uuml;,&#369;,&#361;,&#371;,&#363;,&#373;,&yacute;,&#375;,&yuml;,&#378;,&#380;,&eth;,&thorn;
&aacute;,&agrave;,&#259;,&acirc;,&aring;,&auml;,&atilde;,&#261;,&#257;,&aelig;,&#263;,&#265;,&#269;,&#267;,&ccedil;,&#271;,&#273;,&eacute;,&egrave;,&#277;,&ecirc;,&#283;,&euml;,&#279;,&#281;,&#275;,&#287;,&#285;,&#289;,&#291;,&#293;,&#295;,&iacute;,&igrave;,&#301;,&icirc;,&iuml;,&#297;,&#303;,&#299;,&#305;,&#309;,&#311;,&#312;,&#314;,&#318;,&#316;,&#322;,&#324;,&#328;,&ntilde;,&#326;,&#331;,&oacute;,&ograve;,&#335;,&ocirc;,&ouml;,&#337;,&otilde;,&oslash;,&#333;,&#341;,&#345;,&#343;,&#347;,&#349;,&#351;,&#357;,&#355;,&#359;,&uacute;,&ugrave;,&#365;,&ucirc;,&#367;,&uuml;,&#369;,&#361;,&#371;,&#363;,&#373;,&yacute;,&#375;,&yuml;,&#378;,&#380;,&eth;,&thorn;
</source>
</syntaxhighlight>


==string to array==
==string to array==
<div class="thumb tleft"><google uid="C08" position="right"></google></div>
<syntaxhighlight lang="php">
<source lang="php">
$sUtf= 'éééé'; // string UTF-8
$sUtf= 'éééé'; // string UTF-8
$iSize= strlen($sUtf);
$iSize= strlen($sUtf);
Ligne 159 : Ligne 151 :
   $aChars[$i]= $sUtf[$i];
   $aChars[$i]= $sUtf[$i];
}
}
</source>
</syntaxhighlight>


$aChars outputs:
$aChars outputs:
Ligne 177 : Ligne 169 :
''':-('''
''':-('''


<source lang="php">
<syntaxhighlight lang="php">
$sUtf= 'éééé'; // string UTF-8
$sUtf= 'éééé'; // string UTF-8
$iSize= mb_strlen($sUtf, 'UTF-8');
$iSize= mb_strlen($sUtf, 'UTF-8');
Ligne 184 : Ligne 176 :
       $aChars[$i]= $char;
       $aChars[$i]= $char;
}
}
</source>
</syntaxhighlight>
$aChars outputs:
$aChars outputs:
<pre>
<pre>
Ligne 210 : Ligne 202 :


Avant :
Avant :
<source lang="php">
<syntaxhighlight lang="php">
class Panda extends Ursidae {
class Panda extends Ursidae {
     function Panda($aInit= null)
     function Panda($aInit= null)
Ligne 223 : Ligne 215 :
     }
     }
}
}
</source>
</syntaxhighlight>


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


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


==implode de tableau associatif, array to string==
==implode de tableau associatif, array to string==
Ligne 259 : Ligne 250 :
</pre>
</pre>
No need to s'emmerder.
No need to s'emmerder.


==Google referer key word / mot clés d'un visiteur provenant de google==
==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.
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">
<syntaxhighlight lang="php">
// le referer  
// le referer  
$sReferer = strtolower($_SERVER['HTTP_REFERER']);
$sReferer = strtolower($_SERVER['HTTP_REFERER']);
Ligne 280 : Ligne 270 :
$sMotsClesGoogle= urldecode($sChaineRecherche);
$sMotsClesGoogle= urldecode($sChaineRecherche);
}
}
</source>
</syntaxhighlight>


==Les méthodes magiques==
==Les méthodes magiques==
Ligne 286 : Ligne 276 :


Pour faciliter votre compréhension (et pourquoi pas ?) les exemples seront avec cet objet :
Pour faciliter votre compréhension (et pourquoi pas ?) les exemples seront avec cet objet :
<source lang="php">
<syntaxhighlight lang="php">
class Poulpe extends Octopus {
class Poulpe extends Octopus {
public $iDureeVieMax= 2; /* annees */
public $iDureeVieMax= 2; /* annees */
Ligne 293 : Ligne 283 :
}
}
}
}
</source>
</syntaxhighlight>
Qui n'est autre qu'un poulpe très simple ou ''octopus vulgaris simplex'' en pseudo taxonomie de troquet.
Qui n'est autre qu'un poulpe très simple ou ''octopus vulgaris simplex'' en pseudo taxonomie de troquet.



Dernière version du 8 novembre 2026 à 17:46

Fichier:Borat Great Success.jpg
ah wa wa waa, grand succèèès, PHP langage numéro un dans tout Kazakhstan

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

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

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

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

Unicode vers Html

Par exemple ä est unicodé en "U+00E4" :

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

L'entité html est donc :

ä

Preuve :

 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');"
 ä

En CLI (le fichier doit être encodé en UTF-8) :

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

$sT= 'á, à, &#259;, â, å, ä, ã, &#261;, &#257;, æ, &#263;, &#265;,
&#269;, &#267;, ç, &#271;, &#273;, é, è, &#277;, ê, &#283;, ë, &#279;,
&#281;, &#275;, &#287;, &#285;, &#289;, &#291;, &#293;, &#295;, í, ì,
&#301;, î, ï, &#297;, &#303;, &#299;, &#305;, &#309;, &#311;, &#312;,
&#314;, &#318;, &#316;, &#322;, &#324;, &#328;, ñ, &#326;, &#331;, ó, ò,
&#335;, ô, ö, &#337;, õ, ø, &#333;, &#341;, &#345;, &#343;, &#347;,
&#349;, &#351;, &#357;, &#355;, &#359;, ú, ù, &#365;, û, &#367;, ü,
&#369;, &#361;, &#371;, &#363;, &#373;, ý, &#375;, ÿ, &#378;, &#380;,
ð, þ, á, é, í, ñ, ó';

$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) );
?>

Affichera :

&aacute;,&agrave;,&#259;,&acirc;,&aring;,&auml;,&atilde;,&#261;,&#257;,&aelig;,&#263;,&#265;,&#269;,&#267;,&ccedil;,&#271;,&#273;,&eacute;,&egrave;,&#277;,&ecirc;,&#283;,&euml;,&#279;,&#281;,&#275;,&#287;,&#285;,&#289;,&#291;,&#293;,&#295;,&iacute;,&igrave;,&#301;,&icirc;,&iuml;,&#297;,&#303;,&#299;,&#305;,&#309;,&#311;,&#312;,&#314;,&#318;,&#316;,&#322;,&#324;,&#328;,&ntilde;,&#326;,&#331;,&oacute;,&ograve;,&#335;,&ocirc;,&ouml;,&#337;,&otilde;,&oslash;,&#333;,&#341;,&#345;,&#343;,&#347;,&#349;,&#351;,&#357;,&#355;,&#359;,&uacute;,&ugrave;,&#365;,&ucirc;,&#367;,&uuml;,&#369;,&#361;,&#371;,&#363;,&#373;,&yacute;,&#375;,&yuml;,&#378;,&#380;,&eth;,&thorn;

string to array

$sUtf= 'éééé'; // string UTF-8
$iSize= strlen($sUtf);
for($i=0; $i < $iSize; $i++) {
  	$aChars[$i]=	$sUtf[$i];
}

$aChars outputs:

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

:-(

$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;
}

$aChars outputs:

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

:-)

Cache APC

Kro meugnon!!!<3<3<3
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 :

class Panda extends Ursidae {
    function Panda($aInit= null)
    {
    	if(!empty($aInit)) {
	    	foreach ($aInit as $k => $v) {
				if (!empty($v)) {
					$this->$k= $v;	
				}
			}
    	}
    }
}

Après (on peut garder la signature obsolète) :

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

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.

// 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);
}

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 :

class Poulpe extends Octopus {
	public $iDureeVieMax= 2;	/* annees */

	function Poulpe() {
	}
}

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