Astuces
|
<?php
sleep(1);
?>
php -a
|
Lancer un serveur de développement
|
cd /path/mon/code/php
php -S localhost:8080
|
Écrire dans le fichier de log (/var/log/nginx/error.log)
|
error_log("message");
error_log(print_r($variable, true));
|
|
var_dump($array);
|
 |
Si xdebug est installé, la profondeur d'exploration est limitée par la variable xdebug.var_display_max_depth du fichier /etc/php/conf.d/xdebug.ini |
Les variables globales
|
$a = 1;
$b = 2;
$c = 3;
function test() {
global $b;
echo $a;
echo $b;
echo $GLOBALS['c'];
}
|
Portée des variables
Les fonctions
|
function ma_fonction($argument1, $argument2="2") {
return "ok : $argument1 $argument";
}
echo ma_fonction("1");
|
if
|
if ($a == $b && $a != $b || !&a) { .. }
elseif ($a > $b && $a <= $b) { ... }
else { ... }
|
Retourne vrai si $variable n'existe pas ou si elle est vide.
Étant considéré comme vide:
- "" (une chaîne vide)
- 0, 0.0, "0"
- NULL, FALSE
- array() (un tableau vide)
- $var; (une variable déclarée, mais sans valeur)
|
if (empty($variable)) { ... }
|
isset, is_null
|
if (isset($variable)) { ... }
if (is_null($variable)) { ... }
|
test type
|
if (is_bool($variable)) { ... }
if (is_string($variable)) { ... }
if (is_numeric($variable)) { ... }
if (is_array($variable)) { ... }
if (is_object($variable)) { ... }
|
for
|
for ($i = 1; $i <= 10; $i++) {
echo $i;
break;
continue;
}
|
Tableau / Array
|
$tableau = array(1, 2, 3);
foreach ($tableau as $value) {
echo $value;
}
if (in_array(1, $tableau)) { ... }
$taille = count($tableau);
array_push($tableau, 4);
array_fill($start_index , $number , $value);
implode("|", $tableau)
|
|
$new_array = array_map(
function ($value) {
return $value * 2;
},
range(1, 5)
);
$array_1 = array(1, 2, 3);
$array_2 = array(4, 5, 6);
$new_array = array_map(
function ($value_1, $value_2) {
return $value_1 + $value_2;
},
$array_1,
$array_2
);
|
Dictionnaire
|
$tableau = array('clé1' => 1, 'clé2' => 2);
echo $tableau['clé1'];
$tableau['clé3'] = 3;
if (array_key_exists('clé1', $tableau)) { ... }
foreach (array_keys($tableau) as $key) { ... }
foreach (array_values($tableau) as $value) { ... }
if(($key = array_search($item, $items, true)) !== FALSE) {
}
echo implode('<br>', array_map(
function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
$_SERVER,
array_keys($_SERVER)
));
|
 |
Les clés ne peuvent être que du type integer ou string. |
|
$file_content = file_get_contents("mon_fichier.txt");
if ($file_content === false)
echo "impossible de lire le contenu du fichier mon_fichier.txt";
|
|
if (file_put_contents("mon_fichier.txt", "données", FILE_APPEND) === false)
echo "impossible d'écrire dans le fichier mon_fichier.txt";
|
 |
Si le fichier n'existe pas il est créé.
Le contenu du fichier est écrasé si FILE_APPEND n'est pas utilisé. |
Manipulation de fichiers et de dossiers
|
if (is_link($path)) {
$target = readlink($path);
}
elseif (is_dir($path)) { ... }
elseif (is_file($path)) { ... }
|
 |
is_dir et is_file résolvent les liens symboliques. |
|
$files = scandir('dossier');
for ($i = 2; $i <= count($files); $i++) {
echo "dossier/$files[$i]";
}
|
Ancienne méthode
|
if ($handle = opendir($path_to_directory)) {
while (($file = readdir($handle)) !== false) {
$path = $directory.'/'.$file;
if (is_file($path))
{
echo "$path<br>";
}
}
closedir($handle);
}
|
 |
Avec .. , is_file peut causer l'erreur: open_basedir restriction in effect. File(/path/..) is not within the allowed path(s) |
Opérations sur les path
|
basename("/chemin/vers/un/dossier");
basename("/chemin/vers/un/fichier.ext");
basename("/chemin/vers/un/fichier.ext", ".ext");
dirname("/chemin/vers/un/dossier");
dirname("/chemin/vers/un/fichier.ext");
$path_parts = pathinfo('/chemin/vers/un/fichier.ext');
$path_parts['dirname'];
$path_parts['basename'];
$path_parts['extension'];
$path_parts['filename'];
pathinfo('/chemin/vers/un/fichier.ext', PATHINFO_EXTENSION);
realpath('.');
|
String
Concaténer des string
|
$phrase = "$mot1 mot_deux $mot3";
$phrase = $mot1 . 'mot_deux'. $mot3;
$phrase .= "mot quatre";
|
Remplacement dans un string
|
$var = str_replace(" ", "%20", "dossier/mon fichier.jpg");
$pattern = '/\[.+?\]/i';
preg_replace($pattern, '','mon [petit] fichier');
|
Découper un string
|
substr("abcdef", 0, 2);
substr("abcdef", -2);
substr("abcdef", -3, 1);
|
MAJUSCULE / minuscule
|
$var = strtolower('PHP');
$var = strtoupper('php');
|
|
$chiffres_string = "1,2,3";
$chiffres_tableau = explode(",", $chiffres_string);
echo $chiffres_tableau[0];
echo $chiffres_tableau[1];
|
Expressions rationnelles
|
if (preg_match('/id=(\d+)$/', "http://www.url.com?id=666", $matches))
{
$id = $matches[1];
}
|
Supprime au début et à la fin de la chaine les caractères spécifiés (par défaut: espace, \t, \n, \r, \0, \x0B).
|
trim(' un mot - en passant - ', ' -');
|
DateTime
|
$date = new DateTime('1984-01-30');
$date = date_create('1984-01-30');
$date = date_create_from_format('d/m/Y', '13/12/2013');
echo $date->format('d F Y');
echo date_format($date, 'd F Y');
setlocale(LC_TIME, "fr_CH");
echo strftime('%e %B %Y' ,$date->getTimestamp());
|
date(): It is not safe to rely on the system's timezone settings
date(): It is not safe to rely on the system's timezone settings.
You are *required* to use the date.timezone setting or the date_default_timezone_set() function.
In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier.
We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.
L'utilisation de la fonction date() sans avoir définit la timezone entraine l’apparition de ce warning.
/etc/php/php.ini
|
date.timezone = Europe/Paris
|
|
date_default_timezone_set("Europe/Paris");
|
POO
Classe
|
class MaClasse extends ClasseParente
implements MonInterface {
private $Attribut = 0;
public function Méthode() {
return $this->Attribut++;
}
const CONSTANT = 'valeur constante';
public static $StaticAttribut = 'variable statique';
function __construct() { ... }
function __construct($var1)
{
$this->Attribut = $var1;
}
function __destruct() { ... }
}
$ma_classe = new MaClasse();
$ma_classe->Attribut;
$ma_classe->Méthode();
MaClasse::$StaticAttribut;
|
Les classes et les objets
 |
Par défault les méthodes et attribut sont public Les constantes sont exclusivements public |
 |
Une classe ne peut être déclarée static. On utilisera abstract à la place et des attributs static ou const. |
 |
Les attributs static ne sont persistants qu'au sein d'une même page.
Pour faire persister des données au travers de différentes pages, il faut utiliser Session |
Permet d'éviter d'avoir à écrire une longue liste d'inclusions de fichier de classes au début de chaque script.
La fonction __autoload() sera automatiquement appelée lors de l'utilisation d'une classe ou interface qui n'est pas encore définie. Cette méthode donne une dernière chance pour inclure une définition de classe.
|
spl_autoload_register(function ($class) {
require_once $class . '.php';
});
function __autoload($class) {
require_once $class . '.php';
}
|
Enum
|
abstract class Enum {
private static $constCache = NULL;
private static function getConstants() {
if (self::$constCache === NULL) {
$reflect = new ReflectionClass(get_called_class());
self::$constCache = $reflect->getConstants();
}
return self::$constCache;
}
public static function DisplayName($value) {
return array_keys(self::getConstants())[$value - 1];
}
public static function AllValues() {
return array_keys(self::getConstants());
}
}
abstract class MonEnum extends Enum {
const Valeur1 = 1;
const Valeur2 = 2;
}
echo MonEnum::DisplayName(MonEnum::Valeur1);
foreach (MonEnum::AllValues() as $value) { ... }
|
Trait
|
trait MonTrait {
public function Méthode() { ... }
public static function MéthodeStatic() { ... }
public $Attribut = 1;
}
class MaClasse {
use MonTrait;
}
MaClasse::MéthodeStatic();
$maClasse = new MaClasse();
$maClasse->Méthode();
|
 |
A la différence de l'héritage, si un trait a une propriété publique, chaque classe qui utilise le trait a une instance indépendante (non partagée) de cette propriété. |
|
$reflection = new ReflectionClass('MaClasse');
$constants = $reflection->getConstants();
$classe = get_class();
$classe = get_class($this);
$classe = get_called_class();
|
get_class
|
exec("command arg1 arg2 2>&1", $output, $return_var);
if ($return_var == 0) { }
putenv('LC_TIME=fr_CH');
|
JSON
|
'movie' =>
array (size=2)
'title' => string 'Las Vegas parano'
'originalTitle' => string 'Fear and Loathing in Las Vegas'
|
|
$data = json_decode($json, true);
$data['movie']['title'];
$mon_objet = new MaClasse();
foreach ($json as $key => $value) {
$mon_objet->{$key} = $value;
}
$json = json_encode($objet, JSON_PRETTY_PRINT);
|
|
class MaClasse implements JsonSerializable {
public function jsonSerialize() {
return [ 'movie' => [
'title' => $this->Title,
'originalTitle' => $this->OriginalTitle
]];
}
}
$maClasse = new MaClasse();
$json = json_encode($maClasse, JSON_PRETTY_PRINT);
|
json_decode
json_encode
DOM
|
$dom = DOMDocument::loadXML('<node attribut="attribut value">text content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
echo $node->textContent;
$node->removeChild($node->firstChild);
$node->appendChild(new DOMText('new content'));
$node->getAttribute('attribut');
$node->setAttribute("attibut", "new value");
$node->removeAttribute('attribut');
|
XPath
|
$dom = new DOMDocument;
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$query = '//div';
$entries = $xpath->query($query);
echo $entries->length." resultats.<br/>";
foreach ($entries as $entry) {
echo "$entry->tagName ; $entry->nodeValue<br/>";
}
if($entries->length > 0)
{
echo $dom->saveHTML($entries->item(0));
}
|
Session
Permet un stockage temporaire de données par utilisateur.
|
<?php
spl_autoload_register(function ($class) {
require_once $class . '.php';
});
session_start();
?>
<html>
<body>
<?php
$_SESSION['clé'] = 'valeur';
|
require vs include
En cas d'échec:
- include génère un warning et le script continue
- require génère une erreur et le script stoppe
Les variantes include_once et require_once permettent de s'assurer que le fichier ne sera inclut qu'une seule fois.
Stocker le code d'une page dans une variable
|
$html = file_get_contents("http://url");
|
Afficher les erreurs dans la page
|
ini_set('display_errors', 1);
|
/etc/php/php.ini
|
display_errors = on
|
Input Form
|
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Texte: <input type="text" name="identifiant du champs input">
<select name="identifiant du select">
<option value="">--- Select ---</option>
<?php
foreach ($tous_les_choix as $choix) {
echo '<option value="' . $choix . '">' . $choix . '</option>';
}
?>
</select>
<input type="submit" name="identifiant du bouton" value="texte affiché dans le bouton">
</form>
<?php
$texte = $_POST["identifiant du champs input"];
if (isset($_POST["identifiant du bouton"])) { /* test si on a appuyé sur le bouton */
echo "TEXTE: $texte";
}
?>
|
 |
Si l'on utilise la méthode get le dictionnaire contenant les valeurs sera $_GET |
POST
++
|
$a = 1;
$a++;
echo "Variable a : $a";
echo "Variable a : ".$a++;
|
Opérateurs d'incrémentation et décrémentation
|
composer require athari/yalinqo
|
|
$id = 5;
$i = from($items)->single('$v["id"] == $id');
$i = from($items)->single(function($item) use($id) {
return $item->id == $id;
});
|
Nombre aléatoire
|
$random_number = mt_rand(0, 10);
|
Tester si une variable est numérique
|
if (is_numeric ($maVariable))
if (is_int ($maVariable))
|
Informations sur le serveur
|
<?php phpinfo(); ?>
|
$_SERVER variable
|
'UNIQUE_ID' => string 'UlLqJ8CoAAEAAB7dBHEAAAAE' (length=24)
'HTTP_HOST' => string 'xxx' (length=3)
'HTTP_USER_AGENT' => string 'Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0' (length=68)
'HTTP_ACCEPT' => string 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (length=63)
'HTTP_ACCEPT_LANGUAGE' => string 'fr-fr,en-us;q=0.7,en;q=0.3' (length=26)
'HTTP_ACCEPT_ENCODING' => string 'gzip, deflate' (length=13)
'HTTP_DNT' => string '1' (length=1)
'HTTP_CONNECTION' => string 'keep-alive' (length=10)
'PATH' => string '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin' (length=49)
'SERVER_SIGNATURE' => string '<address>Apache/2.2.25 (Unix) DAV/2 PHP/5.5.4 mod_perl/2.0.8 Perl/v5.18.1 Server at xxx Port 80</address>
' (length=106)
'SERVER_SOFTWARE' => string 'Apache/2.2.25 (Unix) DAV/2 PHP/5.5.4 mod_perl/2.0.8 Perl/v5.18.1' (length=64)
'SERVER_NAME' => string 'xxx' (length=3)
'SERVER_ADDR' => string '127.0.0.1' (length=9)
'SERVER_PORT' => string '80' (length=2)
'REMOTE_ADDR' => string '127.0.0.1' (length=9)
'DOCUMENT_ROOT' => string '/srv/http/xxx' (length=13)
'SERVER_ADMIN' => string 'you@example.com' (length=15)
'SCRIPT_FILENAME' => string '/srv/http/xxx/index.php' (length=23)
'REMOTE_PORT' => string '42707' (length=5)
'GATEWAY_INTERFACE' => string 'CGI/1.1' (length=7)
'SERVER_PROTOCOL' => string 'HTTP/1.1' (length=8)
'REQUEST_METHOD' => string 'GET' (length=3)
'QUERY_STRING' => string '' (length=0)
'REQUEST_URI' => string '/index.php' (length=10)
'SCRIPT_NAME' => string '/index.php' (length=10)
'PHP_SELF' => string '/index.php' (length=10)
'REQUEST_TIME_FLOAT' => float 1381165607.717
'REQUEST_TIME' => int 1381165607
|
URL de la page courante
|
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? 'https' : 'http';
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$params = $_SERVER['QUERY_STRING'];
$currentUrl = $protocol . '://' . $host . $script . '?' . $params;
|
Permet d'afficher les caractères accentués.
|
<?php
header('Content-Type: text/html; charset=utf-8');
?>
|
Rediriger automatiquement vers une autre page
|
<?php
header("Location: dossier/");
header("Location: http://un.autre.site/dossier/");
exit();
?>
|
|
location.href = http:
|
|
<META http-equiv="refresh" content="5;URL=http://un.autre.site/dossier/">
|
Master Page
MasterPage.php
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
echo $content;
?>
</body>
</html>
|
Page1.php
|
<?php
$content .= '<link href="style.less" rel="stylesheet/less" type="text/css" />';
$content .= '<script src="less-1.5.0.min.js"></script>';
$content .= 'Contenu de la page 1';
include('MasterPage.php');
?>
|
Web API
|
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Content-Type: application/json; charset=UTF-8");
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$arg1 = filter_input(INPUT_GET, 'arg1', FILTER_SANITIZE_STRING);
$arg2 = filter_input(INPUT_GET, 'arg2', FILTER_SANITIZE_STRING);
switch ($arg1) {
case 'xxx':
MakeResponse('data');
break;
case 'yyy':
MakeResponse('data');
break;
default:
MakeResponse('error', 400);
}
}
else if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$body = file_get_contents('php://input');
$body = json_decode(file_get_contents("php://input"));
}
function MakeResponse($data, $response_code = 200) {
http_response_code($response_code);
echo json_encode($data);
}
|
/etc/nginx/nginx.conf
|
server {
listen 80;
server_name mywebapiserver;
root /srv/http/mywebapiserver;
index index.php;
rewrite ^/api/([^/]+)/([^/]+)/?$ /api/api.php?arg1=$1&arg2=$2 last;
location = /api/api.php {
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index api.php;
include /etc/nginx/fastcgi.conf;
}
}
|
Téléchargez les sources
Online PHP interpreter
codepad viper-7