php and mysql tips and tricks, dc 2007

39
PHP/MySQL tips and tricks Washington DC, USA, November 7th 2007

Upload: seguy-damien

Post on 18-May-2015

5.343 views

Category:

Technology


3 download

DESCRIPTION

Like opening a long hidden treasure chest, this session will bring many jewels back to the programming light. We'll cover a number of lesser known PHP function and MySQL functionalities, that will help at daily tasks. They will be applied in various fields, including security, performances, standard compliance and simply fun to program.

TRANSCRIPT

Page 1: PHP and MySQL Tips and tricks, DC 2007

PHP/MySQL tips and tricksWashington DC, USA, November 7th 2007

Page 2: PHP and MySQL Tips and tricks, DC 2007

Agenda

Tips and Tricks from PHPNo need for anything else than standard distributionAll for PHP 5( but lots of it is also valid in PHP 4 )

No petting the elePHPant until the end of the session

Page 3: PHP and MySQL Tips and tricks, DC 2007

Who is speaking?

Damien SéguyNexen Services, Open Source hosting companyPHP / MySQL expert servicesRedacteur en chef of www.nexen.netPHather of thousands plush Elephpants

http://www.nexen.net/english.php

Page 4: PHP and MySQL Tips and tricks, DC 2007

Nod when you know about it

Page 5: PHP and MySQL Tips and tricks, DC 2007

PHP 5 : PHP 4 on diet?

PHP 5 : 67 extensions bundledPHP 5 : 2144 functionsPHP 5 : 158 classes....(watch for DateTime)

PHP 4 : 77 extensions bundledPHP 4 : 2459 functionsPHP 4 : 3 classes

Page 6: PHP and MySQL Tips and tricks, DC 2007

Random stuff

<?php$a = range('d','a');shuffle($a);

print_r($a);

print str_shuffle('abcdef');// eabdcf

print_r(array_rand($a,3));?>

Array( [0] => c [1] => d [2] => b [3] => a)Array( [0] => 0 [1] => 1 [2] => 3)

Page 7: PHP and MySQL Tips and tricks, DC 2007

Random stuff

rand() and mt_rand()

array_rand() : extract info from an array

extract keys!

shuffle() : shuffle an array before deal

str_shuffle() : shuffle a string

Page 8: PHP and MySQL Tips and tricks, DC 2007

Arrays combinaisons

array_combine() : turn two arrays into one

Inverse to array_keys() and array_values()<?php$a = array('green', 'red', 'yellow');$b = array('avocado', 'apple', 'banana');$c = array_combine($a, $b);

print_r($c);?>

Array( [green] => avocado [red] => apple [yellow] => banana)

Page 9: PHP and MySQL Tips and tricks, DC 2007

array_combine() applied

<?php $a = range('e','a');

$shuffled_a = array_combine( array_rand($a,5),  array_values($a)); // eabdcf

shuffle($a); ?>

Page 10: PHP and MySQL Tips and tricks, DC 2007

Arrays as SQL

sort ∅ r u

∅ ∅ r u

k k kr uk

a a ar ua

Page 11: PHP and MySQL Tips and tricks, DC 2007

Slicing array in chunks : PHP

<?php   $array = range(1,5);   print_r(array_chunk($array,2)); ?>

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

[1] => Array ( [0] => 3 [1] => 4 )

[2] => Array ( [0] => 5 )

)

Page 12: PHP and MySQL Tips and tricks, DC 2007

Slicing array in chunks : SQL

mysql> SET @a := 1; mysql> SELECT @a, GROUP_CONCAT(i) FROM integers GROUP BY ROUND((@a := @a + 1) / 4 , 0); +------+-----------------+| @a | group_concat(i) |+------+-----------------+| 2 | 0,1,2,13 | | 6 | 4,15,6,7 | | 12 | 11,8,9 | +------+-----------------+3 rows in set (0.00 sec)

+------+| i |+------+| 0 | | 1 | | 2 | | 13 | | 4 | | 15 | | 6 | | 7 | | 8 | | 9 | | 11 | +------+

Page 13: PHP and MySQL Tips and tricks, DC 2007

JOIN is faster than LIMIT

mysql> SELECT cols FROM TABLE LIMIT 1000, 10;

Page 14: PHP and MySQL Tips and tricks, DC 2007

JOIN is faster than LIMIT

mysql> CREATE TABLE `table_limit` ( `row` int(10) unsigned NOT NULL AUTO_INCREMENT, `id` int(11) unsigned DEFAULT NULL, UNIQUE KEY `id` (`id`) );

mysql> INSERT INTO table_limit SELECT 0, id FROM table ORDER BY col;

mysql> SELECT col FROM table_limit JOIN table ON bl_content.id = bl_content_nav.id AND table_limit.row BETWEEN @offset AND @offset + 10

Page 15: PHP and MySQL Tips and tricks, DC 2007

JOIN is faster than LIMIT

Page 16: PHP and MySQL Tips and tricks, DC 2007

Arrays sorted as SQL cols

array_multisort() : sort several arrays at once

Works like a ORDER BY

Array( [0] => 2 [1] => 3 [2] => 4 [3] => 5)Array( [0] => d [1] => c [2] => b [3] => a)

<?php$ar1 = array(5,4,3,2);$ar2 = array('a','b','c','d');array_multisort($ar1, $ar2);array_multisort($ar1, SORT_ASC,SORT_STRING, $ar2);?>

Page 17: PHP and MySQL Tips and tricks, DC 2007

GROUP BY PHP!

DISTINCT : array_unique()

COUNT(*) and GROUP BY : array_count_values()

Hint : array_count_values() is always faster that array_unique()...

<?php $array = array(1, "hei", "1", "takk", "hei"); print_r(array_count_values($array));?> Array

( [1] => 2 [hei] => 2 [takk] => 1)

Page 18: PHP and MySQL Tips and tricks, DC 2007

Hide those loops to me!

<?php  while(list($key, $val) = each($array)) {  print "$key => $val\n"; }

for($i = 0; $i<count($array); $i++) {  print "$i => {$array[$i]}\n"; } ?>

Page 19: PHP and MySQL Tips and tricks, DC 2007

Hide those loops to me!

<?php $array = range(1,3); foreach($array as $id => &$value) {    $value++; } ?>

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

Declare your objects as Iterators

Page 20: PHP and MySQL Tips and tricks, DC 2007

Hidden loops

array_map : apply a function to all elements

array_walk_recursive : same as above, and multi-dimensional

array_filter : extract all elements using a custom function

Page 21: PHP and MySQL Tips and tricks, DC 2007

Fast dir scans

scandir(‘/tmp’, true);

Include name sorting

Replace opendir, readdir, closedir and a loop!

glob(‘*.html’);

Simply move the loop out of sight

Page 22: PHP and MySQL Tips and tricks, DC 2007

Fast dir scans

Array( [0] => sess_um8rgjj10f6qvuck91rf36srj7 [1] => sess_u58rgul68305uqfe48ic467276 [2] => mysql.sock [3] => .. [4] => .)Array( [0] => /tmp/sess_um8rgjj10f6qvuck91rf36srj7 [1] => /tmp/sess_u58rgul68305uqfe48ic467276)

<?phpprint_r(scandir('/tmp/', 1));print_r(glob('/tmp/sess_*'));?>

Page 23: PHP and MySQL Tips and tricks, DC 2007

URL

<?php$url = 'http://login:[email protected]/ path/file.php?a=2+&b%5B%5D= %E5%AF%B9%E4%BA%86%EF%BC%81#ee';$d = parse_url($url);print_r($d);

parse_str($d["query"]);var_dump($GLOBALS["b"]); ?>

Page 24: PHP and MySQL Tips and tricks, DC 2007

URL operations

parse_url()

Break down into details

Do not make any check

parse_str()

Split a query string

Separate and decode, as long as it can

Fills up an array or $GLOBALS

Page 25: PHP and MySQL Tips and tricks, DC 2007

URL

( [scheme] => http [host] => www.site.com [user] => login [pass] => pass [path] => /path/file.php [query] => a=2&b%5B%5D=%E5%AF%B9%E4%BA%86%EF%BC%81 [fragment] => ee)array(1) { [0]=> string(9) "对了!"}

Page 26: PHP and MySQL Tips and tricks, DC 2007

URL validations

scheme : list your own

host : checkdnsrr() to check

path : realpath() + doc root (beware of mod_rewrite)

query : parse_str()

beware of the second argument!

don’t handle &amp;

Page 27: PHP and MySQL Tips and tricks, DC 2007

URL rebuilding

<?phpprint http_build_query( array_merge($_GET , array(' de ' => '对了!')));?>

+de+=%E5%AF%B9%E4%BA%86%EF%BC%81

http_build_query() : PHP 5 only

rebuild your query

takes into account encoding and arrays

Page 28: PHP and MySQL Tips and tricks, DC 2007

URL testing

<?php get_headers('http://localhost/logo.png');?>

Array( [0] => HTTP/1.1 200 OK [1] => Date: Mon, 12 Feb 2007 02:24:23 GMT [2] => Server: Apache/1.3.33 (Darwin) PHP/5.2.1 [3] => X-Powered-By: eZ publish [4] => Last-Modified: Fri, 30 Sep 2005 09:11:28 GMT [5] => ETag: "f6f2a-dbb-433d0140" [6] => Accept-Ranges: bytes [7] => Content-Length: 3515 [8] => Connection: close [9] => Content-Type: image/png)

Page 29: PHP and MySQL Tips and tricks, DC 2007

PHP is dynamic

Variables variables<?php $x = 'y'; $y = 'z'; $z = 'a';

echo $x;  // displays y echo $$x;  // displays z echo $$$x; // displays a ?>

Page 30: PHP and MySQL Tips and tricks, DC 2007

PHP is crazy

Crazy variables

<?php $美国 = 'works'; $êtrânçé = 'works'; ${'Utter madness?'} = 'works'; ${''} = 'works'; ?>

Page 31: PHP and MySQL Tips and tricks, DC 2007

Variables export

var_export() : recreate PHP code for a variable

<?php

$array = array(5,4,3,2);

file_put_contents('file.inc.php', '<?php $x = '. var_export($array, true). '; ?>');?>

array ( 0 => 5, 1 => 4, 2 => 3, 3 => 2,)

Page 32: PHP and MySQL Tips and tricks, DC 2007

Fast file exports

file_put_contents($file_name, $content);

accept contexts and streams

Complementary to file_get_contents()

fputcsv() : create CSV style files

complementary to fgetcsv()

Page 33: PHP and MySQL Tips and tricks, DC 2007

Assertions

Include tests during execution

Assertion are an option (default is on) :

Most clever way than removing than echo/var_dump

Common practice in other languages

Programmation by contract

Page 34: PHP and MySQL Tips and tricks, DC 2007

Assertions

<?php assert_options(ASSERT_CALLBACK,'assert_callback'); function assert_callback($script,$line, $message){    echo 'There is something strange  in your script <b>', $script,'</b> :  line <b>', $line,'</b> :<br />'; exit; }

assert('is_integer( $x );' );   assert('($x >= 0) && ($x <= 10);  //* $x must be from 0 to 10' );   echo "0 <= $x <= 10"; ?>

Page 35: PHP and MySQL Tips and tricks, DC 2007

Debugging

get_memory_usage()

memory_limit is now on by default

Better memory handling

get_peak_memory_usage()

sys_getloadavg() : no more need for exec(’uptime’);

Page 36: PHP and MySQL Tips and tricks, DC 2007

Debugging

get_included_files()

get_defined_constants/functions/vars()

get_declared_classes()

get_debug_backtrace()

function stack and their arguments

file and line calling

Page 37: PHP and MySQL Tips and tricks, DC 2007

Debugging

array(2) {[0]=>array(4) { ["file"] => string(10) "/tmp/a.php" ["line"] => int(10) ["function"] => string(6) "a_test" ["args"]=> array(1) { [0] => &string(6) "friend" }}[1]=>array(4) { ["file"] => string(10) "/tmp/b.php" ["line"] => int(2) ["args"] => array(1) { [0] => string(10) "/tmp/a.php" } ["function"] => string(12) "include_once" }}

Page 39: PHP and MySQL Tips and tricks, DC 2007

Everyone loves PHP