« PHP » : différence entre les versions
m →Liens |
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]] | ||
'''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 == | ||
< | <syntaxhighlight lang="php"> | ||
foreach ($arr as &$value) { | foreach ($arr as &$value) { | ||
$value = $value * 2; | $value = $value * 2; | ||
} | } | ||
</ | </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= | ||
< | <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); | ||
} | } | ||
</ | </syntaxhighlight> | ||
}} | }} | ||
| Ligne 81 : | Ligne 80 : | ||
==Détecter IE <= 6== | ==Détecter IE <= 6== | ||
< | <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 | ||
</ | </syntaxhighlight> | ||
==Unicode vers Html== | ==Unicode vers Html== | ||
Par exemple ä est unicodé en "U+00E4" : | Par exemple ä est unicodé en "U+00E4" : | ||
< | <syntaxhighlight lang="php"> | ||
$ php -r "echo base_convert('00E4',16,10);" | $ php -r "echo base_convert('00E4',16,10);" | ||
228 | 228 | ||
</ | </syntaxhighlight> | ||
L'entité html est donc : | L'entité html est donc : | ||
ä | ä | ||
Preuve : | Preuve : | ||
< | <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');" | ||
ä | ä | ||
</ | </syntaxhighlight> | ||
En CLI (le fichier doit être encodé en UTF-8) : | En CLI (le fichier doit être encodé en UTF-8) : | ||
< | <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) ); | ||
?> | ?> | ||
</ | </syntaxhighlight> | ||
Affichera : | Affichera : | ||
< | <syntaxhighlight lang="html4strict"> | ||
á,à,ă,â,å,ä,ã,ą,ā,æ,ć,ĉ,č,ċ,ç,ď,đ,é,è,ĕ,ê,ě,ë,ė,ę,ē,ğ,ĝ,ġ,ģ,ĥ,ħ,í,ì,ĭ,î,ï,ĩ,į,ī,ı,ĵ,ķ,ĸ,ĺ,ľ,ļ,ł,ń,ň,ñ,ņ,ŋ,ó,ò,ŏ,ô,ö,ő,õ,ø,ō,ŕ,ř,ŗ,ś,ŝ,ş,ť,ţ,ŧ,ú,ù,ŭ,û,ů,ü,ű,ũ,ų,ū,ŵ,ý,ŷ,ÿ,ź,ż,ð,þ | á,à,ă,â,å,ä,ã,ą,ā,æ,ć,ĉ,č,ċ,ç,ď,đ,é,è,ĕ,ê,ě,ë,ė,ę,ē,ğ,ĝ,ġ,ģ,ĥ,ħ,í,ì,ĭ,î,ï,ĩ,į,ī,ı,ĵ,ķ,ĸ,ĺ,ľ,ļ,ł,ń,ň,ñ,ņ,ŋ,ó,ò,ŏ,ô,ö,ő,õ,ø,ō,ŕ,ř,ŗ,ś,ŝ,ş,ť,ţ,ŧ,ú,ù,ŭ,û,ů,ü,ű,ũ,ų,ū,ŵ,ý,ŷ,ÿ,ź,ż,ð,þ | ||
</ | </syntaxhighlight> | ||
==string to array== | ==string to array== | ||
< | <syntaxhighlight 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]; | ||
} | } | ||
</ | </syntaxhighlight> | ||
$aChars outputs: | $aChars outputs: | ||
| Ligne 177 : | Ligne 169 : | ||
''':-(''' | ''':-(''' | ||
< | <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; | ||
} | } | ||
</ | </syntaxhighlight> | ||
$aChars outputs: | $aChars outputs: | ||
<pre> | <pre> | ||
| Ligne 210 : | Ligne 202 : | ||
Avant : | Avant : | ||
< | <syntaxhighlight lang="php"> | ||
class Panda extends Ursidae { | class Panda extends Ursidae { | ||
function Panda($aInit= null) | function Panda($aInit= null) | ||
| Ligne 223 : | Ligne 215 : | ||
} | } | ||
} | } | ||
</ | </syntaxhighlight> | ||
Après (on peut garder la signature obsolète) : | Après (on peut garder la signature obsolète) : | ||
< | <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); | ||
</ | </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. | ||
< | <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); | ||
} | } | ||
</ | </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 : | ||
< | <syntaxhighlight lang="php"> | ||
class Poulpe extends Octopus { | class Poulpe extends Octopus { | ||
public $iDureeVieMax= 2; /* annees */ | public $iDureeVieMax= 2; /* annees */ | ||
| Ligne 293 : | Ligne 283 : | ||
} | } | ||
} | } | ||
</ | </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
PHP est l'acronyme de problème d'hygiène personnelle.
- "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['SERVER_NAME']
- dépend du serveur web. Les directives du serveur Apache le modifie comme ServerName, UseCanonicalName.
- $_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
$files = array(); // Contient la liste des images
$filesn = array('.', '..', '.htaccess', 'b.php'); // Fichiers qu'on ne doit pas prendre en compte dans la liste
// (il faut rajouter tous les noms de fichiers interdits)
$dir = './'; // Répertoire à ouvrir
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
closedir($dh);
$files = array_diff($files, $filesn); // On fait la soustraction des fichiers qu'on ne veut pas prendre en compte
$file = $files[array_rand($files, 1)]; // Un fichier au hasard
$header = 'Content-Type: image/';
$png_pattern = '/\.png$/i'; // Pour déterminer le type de fichier
$jpg_pattern = '/\.jpe?g$/i'; // Extensions possibles: .Png, .jpG, .jpeg, .JpeG, etc.
if (preg_match($png_pattern, $file)) {
$header .= 'png';
$image = imagecreatefrompng($file);
header($header);
imagepng($image);
}
elseif (preg_match($jpg_pattern, $file)) {
$header .= 'jpeg';
$image = imagecreatefromjpeg($file);
header($header);
imagejpeg($image);
}
Utilité : avatar aléatoire, égayer une page...
Eclipse
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= 'á, à, ă, â, å, ä, ã, ą, ā, æ, ć, ĉ,
č, ċ, ç, ď, đ, é, è, ĕ, ê, ě, ë, ė,
ę, ē, ğ, ĝ, ġ, ģ, ĥ, ħ, í, ì,
ĭ, î, ï, ĩ, į, ī, ı, ĵ, ķ, ĸ,
ĺ, ľ, ļ, ł, ń, ň, ñ, ņ, ŋ, ó, ò,
ŏ, ô, ö, ő, õ, ø, ō, ŕ, ř, ŗ, ś,
ŝ, ş, ť, ţ, ŧ, ú, ù, ŭ, û, ů, ü,
ű, ũ, ų, ū, ŵ, ý, ŷ, ÿ, ź, ż,
ð, þ, á, é, í, ñ, ó';
$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 :
á,à,ă,â,å,ä,ã,ą,ā,æ,ć,ĉ,č,ċ,ç,ď,đ,é,è,ĕ,ê,ě,ë,ė,ę,ē,ğ,ĝ,ġ,ģ,ĥ,ħ,í,ì,ĭ,î,ï,ĩ,į,ī,ı,ĵ,ķ,ĸ,ĺ,ľ,ļ,ł,ń,ň,ñ,ņ,ŋ,ó,ò,ŏ,ô,ö,ő,õ,ø,ō,ŕ,ř,ŗ,ś,ŝ,ş,ť,ţ,ŧ,ú,ù,ŭ,û,ů,ü,ű,ũ,ų,ū,ŵ,ý,ŷ,ÿ,ź,ż,ð,þ
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


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
- http://www.addedbytes.com/blog/if-php-were-british
- http://www.prohotesseparis.com/
- Indispensable et mieux que PGP et tellement plus klasse que RSA : Enigma en PHP
- http://www.functions-online.com/unserialize.html