Notes sur PHP

Sources : w3schools, Pierre Giraud

Tutoriel

bloc_notes

  

Le bloc-notes web est un moyen de partager un long texte (code source) rapidement par internet.

Utilisation d'Ajax pour enregistrer subrepticement le contenu du textarea.

Attention cependant : il faut penser à utiliser une système d'authentification pour protéger les données.

TODO : faire des sauvegardes automatiques (toutes les 2 minutes par exemple).

gethint

  

gethint : Exemple d'interaction dynamique javascript/php avec ajax

Cas complet

Source
// ===== Fichier 0.html =====

<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>



// ===== Fichier gethint.php =====

<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL
$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            } else {
                $hint .= ", $name";
            }
        }
    }
}

// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>

list_files

  

Stackoverflow - php list files folders
Voir exemples dans adm

Source php
<?php
function getDirContents($dir, &$results = array()) {
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            $results[] = $path;
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }

    return $results;
}

var_dump(getDirContents('/home/gangand/www/'));
?>

parser

  

Le format XML permet de stocker des données.

Pour parcourir et rechercher des informations dans un fichier XML, ou HTML, on peut utiliser la bibliothèque simple_html_dom.

Bibliothèque recopiée en local

Démo

Exemple court : XML_draillard

Source php
<?php
include ('inc/simple_html_dom.php');
define ('FICHIER_XML', 'data.xml');

echo '<center><h1>Fichier source XML</h1>';
$donnees = charger_XML(FICHIER_XML);
echo '</center>';

function charger_XML($fichier_XML) {
    $html = file_get_html($fichier_XML);
    foreach($html->find('livre') as $livre) {
        foreach($livre->find('titre') as $titre) {
            echo '<p>Titre : '.$titre->innertext.'</p>';
        }
        foreach($livre->find('auteur') as $auteur) {
            echo '<p>Auteur : '.$auteur->innertext.'</p>';
        }
    }
}
?>
Source xml
<livre>
    <titre>Premiers pas en CSS3 et HTML5</titre>
    <auteur>Francis Draillard</auteur>
</livre>

upload

  

Uploader un fichier en ligne de commande.
Cette ligne de commande uploade le fichier sur http://un.site/dossier/reception :
curl -F "avatar=@file_to_upload.jpg" http://un.site/dossier/upload.php

Le fichier file_to_upload.jpg se trouve dans le répertoire courant. avatar est le nom du widget file dans upload.php (voir le code du fichier upload.php).

upload.php
<form method="POST" action="upload.php" enctype="multipart/form-data">
     <!-- On limite le fichier à 200Mo -->
     <input type="hidden" name="MAX_FILE_SIZE" value="200000000">
     Fichier : <input type="file" name="avatar">
     <br>
     <input type="submit" name="envoyer" value="Envoyer le fichier (maxi 200 Mo)">
</form>

<?php
$dossier = 'reception/';
$fichier = basename($_FILES['avatar']['name']);
$taille_maxi = 200000000;
$taille = filesize($_FILES['avatar']['tmp_name']);
$extensions = array('.png', '.png');
$extension = strrchr($_FILES['avatar']['name'], '.');

// Début des vérifications de sécurité...
if(!in_array($extension, $extensions)) // Si l'extension n'est pas dans le tableau
{
     $erreur = 'Vous devez uploader un fichier de type pdf, png, gif, jpg ou jpeg.';
}
if($taille>$taille_maxi)
{
     $erreur = 'Le fichier est trop gros...';
}
if(!isset($erreur)) // S'il n'y a pas d'erreur, on uploade
{
     // On formate le nom du fichier ici...
     $fichier = strtr($fichier,
          'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
          'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
     $fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);

     // Si la fonction renvoie TRUE, c'est que ça a fonctionné...
     if(move_uploaded_file($_FILES['avatar']['tmp_name'], $dossier . $fichier))
     {
          echo 'Upload effectué avec succès pour '. $fichier;
     }
     else // Sinon (la fonction renvoie FALSE).
     {
          echo 'Echec de l\'upload pour '. $fichier;
     }
}
else
{
     echo $erreur;
}
?>

sqlite3

create_db.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');

// NOK : https://www.phpfacile.com/apprendre_le_php/php_et_sqlite
$base = 'boulangeries.sqlite';

/**
 * OK : https://www.php.net/manual/fr/sqlite3.open.php
 * Exemple simple qui étend la classe SQLite3 et change les paramètres
 * __construct, puis, utilise la méthode de connexion pour initialiser la
 * base de données.
 */

class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('boulangeries.db');
    }
}

$db = new MyDB();

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('Ceci est un test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());

?>

Veille

laravel

What is the dark side of coding bootcamps? I didn’t attend a coding bootcamp, but I do hire coding bootcamp graduates (and non-coding bootcamp graduates.) Here’s my perspective on the dark side of that industry. One thing you might consider is the possibility of failing out. Bootcamps are both expensive and very intense and the reality is that those who are pretty much guaranteed to pass are the same people who can successfully teach themselves to code using cheap and free online resources. In a lot of bootcamps, if you’re struggling in the middle and the teachers lose confidence in you they will kick you out. Usually this comes with a partial refund and an invitation to repeat the course… if you can pay for that first part of the course again. This can raise the cost of a code camp to over $25,000 or even $30,000 depending on the camp. I would really think hard about if the value of the camp justifies that kind of expenditure. But if you don’t repeat the course, you’re just out $5,000 or $10,000. In return for that money you get… nothing. Only a basic skill set that you could have learned online for free. Remember, 100% of what you can learn at a coding camp is available via online resources. Some are free, some are very cheap. It is possible to recreate the curriculum of a good code camp on Udemy for under $50. Code camps basically provide three points of value: They provide instructors that you can ask for help when you get stuck They provide accountability and they push you at a fast pace (which has its downsides. Most code camp grads have only a shallow understanding of development because they learn it very quickly.) They provide help with getting your first job. This is probably the biggest reason to go to a camp. If they have a good network of hiring partners, that’s a big deal. But if you fail out, you lose all those benefits and you most likely gain a not-insignificant amount of debt. Another aspect of the dark side of coding camps is that many (perhaps most) employers don’t really care about them. In my current role, I hire new developers regularly. From my point of view, whether you taught yourself or went to a code camp makes exactly zero difference. All I want from a junior developer is to see a good portfolio of projects, a solid understanding of one or two programming languages, and a working knowledge of SQL and the tools you’ll need to get the job done (Git, an IDE, etc.) There is one other thing I want to see: passion. I want a junior developer to have a deep interest in code and in building projects. A self-taught developer has a big leg up in this regard. A code camp graduate might have passion… but also might just be trying to jump to a higher income bracket. There’s nothing wrong with that, but I don’t want to invest the kind of resources it takes to train a junior developer if that’s all they’ve got. My honest recommendation is that you first try to teach yourself to code before signing up at a coding bootcamp. If you’re going into, say, web development, do the free HTML, CSS, and JavaScript courses at Codecademy. Then build a few projects, like an HTML calculator and a web application that can pull from the YouTube API to show you the top comedy videos of the week. These aren’t easy projects for beginners, but until you’ve done them (or the equivalent) you really don’t understand the basics. Then try a Udemy course like Colt Steele’s Web Development Bootcamp. You can grab that for $12 if you Google “Udemy Coupon.” Then try his courses on MySQL and React. Colt is a good teacher, and you’ll probably get a lot out of his courses. Then try building a few full stack web applications. Try something like a basic CMS or a social media app or a chat application or an eCommerce site. THEN see if a code camp still has value. If it seems like it does, you’ll be prepared for success. Good luck.

Divers

maths

Distance entre deux points géodésiques

function distance_geodesie(...)
$depart = array(
	'latitude'  => 49.243167,
	'longitude' => 4.022505);
$arrivee = '49.343, 4.122';
$distance = distance_calcul($depart, $arrivee);

function distance_calcul($depart, $geodesie) {	// distance approximative
	// selon le théorème de Pythagore
	// évaluation personnelle : latitude 1km pour 0.009045, longitude 1km pour 0.013778
	$lati_depart = $depart['latitude'];
	$long_depart = $depart['longitude'];

	$g = explode(', ', $geodesie);
	$lati_fin = $g[0];
	$long_fin = $g[1];

	$d1 = intval(abs($lati_depart - $lati_fin) / 0.009045 * 1000);
	$d2 = intval(abs($long_depart - $long_fin) / 0.013778 * 1000);
	$total = pow($d1, 2) + pow($d2, 2);
	$d3 = intval(sqrt($total));

	return $d3;

cache

Mise en cache page php

Directives concernant la mise en cache
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date dans le passé
?>