Table des matières

PHP Tips & Tricks

DateTime

Php => Mysql => Php

 $mysqldate = date( 'Y-m-d H:i:s', $phpdate );

 $phpdate = strtotime( $mysqldate );

strftime

le paramètre %e pour mettre le jour du mois sur 1 seul chiffre (1 à 31) ne fonctionne pas avec Php/Windows. La raison est que strftime n'est pas portable et la doc php n'est donc pas correcte pour tous les OS.

Voir:

La solution pour le %e : remplacer par “%#d”

Gestion des erreurs

Exception

http://www.zend.com/php5/articles/php5-exceptions.php

Sécurité

Strong cryptography in PHP: Use standard algorithms, Key space, Kerchoof’s principle, Don’t use rand() or mt_rand(), Use a salt value in hash functions, Size and strength of the passwords, Don’t use plaintext passwords as key for ciphers.

Divers

DocComment & ReflectionClass

Une démonstration de la récupération des commentaires Advanced Documentation With Reflection In PHP 5, mais obsolète car utilise la fonction php_check_syntax() qui n'est plus dans php depuis php 5.0.4

phpDocumentor home page

See the example at de3.php.net/manual/en/reflectionclass.getdoccomment.php - if you want to parse files for classes, you can use github.com/theseer/Autoload/blob/master/src/classfinder.php and to iterate over directories you use de3.php.net/manual/en/class.recursivedirectoryiterator.php

RegEx

syntaxe adresse email

function mail_checksyntax( $email )
{
  if( isset($email)
  && eregi('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$', $email) )
  {
    return true ;
  }
  return false ;
}

Voir aussi Vos applications valident-elles correctement les adresses e-mail ?, Mail::RFC822::Address: regexp-based address validation

Collation caractères unicode

Pour prendre les caractères accentués ou autres de la langue française: é, è, ê, ù, ç, É, À, … Utiliser la classe de caractères [:word:] et le modifier u (pour activer la collation unicode).

 // match les caractères français et espace et tiret:
 /^[[:word:] \-]+$/u

Pour comparer des mots avec caractères accentués (diacritics) sans tenir compte des accents:

$s1 = 'en été ça va là' ;
$s2 = 'en ÉTE Ça va Là' ;
$s1 = strtolower( iconv( 'UTF-8', 'ASCII//TRANSLIT//IGNORE',$s1) );
$s2 = strtolower( iconv( 'UTF-8', 'ASCII//TRANSLIT//IGNORE',$s2) );
echo 'compare = ', var_export( ($s1==$s2), true),"\n" ;

Cross Platform

if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
  $s_eol = "\r\n";
} elseif (strtoupper(substr(PHP_OS, 0, 3) == 'MAC')) {
  $s_eol = "\r";
} else {
  $s_eol = "\n";
}

XML

A introductory tutorial on simplexml can be found here:

XSLT

<xsl:text disable-output-escaping="yes"> &amp;nbsp;</xsl:text>

fonctionne mieux que CDATA …

Pointeur de fonction

http://mmmm.free.fr/doc/pointfunc.html

Singleton

Singleton

Manipulation fichier Excel

Le package Spreadsheet_Excel_Writer

/usr/local/php5/bin/pear -d preferred_state=beta install OLE
/usr/local/php5/bin/pear -d preferred_state=beta install Spreadsheet_Excel_Writer

Mysqlnd

mysqlnd plugins for PHP in practice: example on how to write a plugin for mysqlnd.

PHP: Transparent load balancing and sharding with mysqlnd: You want some client-side MySQL load balancing with and without sharding for your PHP application? PHP 5.3 has something to offer for you. It is free. It requires no to very little changes to your applications.

Network

Wake On Lan (WOL)

      # Wake on LAN - (c) HotKey@spr.at, upgraded by Murzik
      # Modified by Allan Barizo http://www.hackernotcracker.com
      flush();
      function WakeOnLan($addr, $mac,$socket_number) {
        $addr_byte = explode(':', $mac);
        $hw_addr = '';
        for ($a=0; $a <6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
        $msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
        for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
        // send it to the broadcast address using UDP
        // SQL_BROADCAST option isn't help!!
        $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
        if ($s == false) {
          echo "Error creating socket!\n";
          echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
          return FALSE;
          }
        else {
          // setting a broadcast option to socket:
          $opt_ret = socket_set_option($s, 1, 6, TRUE);
          if($opt_ret <0) {
            echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
            return FALSE;
            }
          if(socket_sendto($s, $msg, strlen($msg), 0, $addr, $socket_number)) {
            echo "Magic Packet sent successfully!";
            socket_close($s);
            return TRUE;
            }
          else {
            echo "Magic packet failed!";
            return FALSE;
            }
 
          }
        }
      // Port number where the computer is listening. Usually, any number between 1-50000 will do. Normally people choose 7 or 9.
      $socket_number = "7";
      // MAC Address of the listening computer's network device
      $mac_addy = "00:12:4G:SF:12:13";
      // IP address of the listening computer. Input the domain name if you are using a hostname (like when under Dynamic DNS/IP)
      $ip_addy = gethostbyname("myhomeserver.dynamicdns.org");
 
      WakeOnLan($ip_addy, $mac_addy,$socket_number)

Import gros fichier

Upload large file.

Php side

To use with Laravel and JS libraries look at laravel-chunk-upload

Nginx side
Client side (chunking)

Cross-site chunked uploads: by default, browsers don't allow all headers used for cross-site file uploads, if they are not explicitly defined as allowed with the following server-side headers:

Access-Control-Allow-Headers Content-Type, Content-Range, Content-Disposition