php tips and tricks

36
PHP tips and tricks Skien, Norge, June 7th 2007

Upload: seguy-damien

Post on 18-May-2015

17.296 views

Category:

Technology


3 download

DESCRIPTION

With over 3400 available built-in function, PHP offers a tremendously rich environment. Yet, some of these functions are still unknown to most programmers. During this session, Damien Seguy will highlight a number of functions that are rarely used in PHP, but are nonetheless useful and available within standard distributions.

TRANSCRIPT

Page 1: PHP tips and tricks

PHP tips and tricksSkien, Norge, June 7th 2007

Page 2: PHP tips and tricks

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 )

The month of PHP functions

Page 3: PHP tips and tricks

Who is speaking?

Damien SéguyNexen Services, eZ publish silver partner for hostingPHP / MySQL servicesRedacteur en chef of www.nexen.netPhather of an plush Elephpant

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

Page 4: PHP tips and tricks

Nod when you know about it

Page 5: PHP tips and tricks

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 6: PHP tips and tricks

Random stuff

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

print_r($a);

print_r(array_rand($a,3));

print str_shuffle('abcdef');// eabdcf?>

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

Page 7: PHP tips and tricks

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 8: PHP tips and tricks

Arrays combinaisons

array_combine() : turn two arrays into one

PDO::FETCH_KEY_PAIR : combine 2 columns in a hash

<?php $html = file_get_contents("http://www.php.net/");

//'<a href="http://php.net">PHP</a>'; if (preg_match_all('#<a href="(http://[^\"/\?]+/).*?>(.*?)</a>#s', $html, $r)) {     $liste = array_combine($r[2], $r[1]); } print_r($liste);

?>

Page 9: PHP tips and tricks

Arrays as SQL

array_count_values() : makes easy stats

Works like a GROUP BY and COUNT()

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

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

sort ∅ r u∅ ∅ r uk k kr uka a ar ua

Page 10: PHP tips and tricks

Arrays as SQL

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 11: PHP tips and tricks

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 12: PHP tips and tricks

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 13: PHP tips and tricks

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

Fill up an array or globals

Page 14: PHP tips and tricks

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 15: PHP tips and tricks

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 16: PHP tips and tricks

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 17: PHP tips and tricks

URL rebuilding

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

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

http_build_query()

rebuild your query

takes into account encoding and arrays

Page 18: PHP tips and tricks

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 19: PHP tips and tricks

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 20: PHP tips and tricks

Variable constants

Still one definition

Dynamic constant value

<?php   define ("CONSTANT", 'eZ Conference');   echo CONSTANT;   echo constant("CONSTANT");  ?>

See the runkit to change constants...

Page 21: PHP tips and tricks

Juggling with variables

Compact() and extract()<?php   $x = 'a'; $y = 'b';   $z = compact('x','y');   // $z = array('x'=> 'a', 'y' => 'b'); 

$r = call_user_func_array('func', $z);  // calling func($x, $y); 

extract($r);  // $x = 'c'; $y = 'd'; $t = 'e'; list($x, $y, $t) = array_values($r); ?>

Page 22: PHP tips and tricks

Variable functions

<?php  $func = 'foo'; $foo = 'bar'; $class = 'bb';

 $func($foo); // calling foo with bar call_user_func($func, $foo);// same as above

 call_user_func(array($class, $func), $foo);  // now with objects! $class->$func($foo); // same as above ?>

Page 23: PHP tips and tricks

Variable functions

<?php $func = 'f'; // a function // beware of langage construct such as empty()

$func = array('c','m'); // a static call to class c

$func = array($o,'m'); // a call to object o

call_user_func($func, $foo);?>

Page 24: PHP tips and tricks

Object magic

__autoload() : load classes JIT

__sleep() and __wakeup()

Store object and ressources in sessions

__toString() : to turn an object to a string

__toArray() : get_object_vars($object);

__toInteger() : may be?

Page 25: PHP tips and tricks

Output buffering

<?phpob_start("ob_gzhandler");echo "Hello\n";setcookie("c", "v");ob_end_flush();?>

Avoid ‘already sent’ bug

Clean it : tidy

Compress it : gz

Cache it

Page 26: PHP tips and tricks

Caching

if ( filemtime($cache)+3600 < time()) {     include($cachefile);     exit; } ob_start();

  $content = ob_get_contents();    file_put_contents('cache', $contents);   ob_end_flush();

auto_prepend :

auto_append :

Auto-caching upon 404 error pages

Page 27: PHP tips and tricks

Connexion handling

PHP maintains the connexion status

0 Normal; 1 Aborted; 2 Timeout

ignore_user_abort() to make a script without interruption

connexion_status() to check status

Page 28: PHP tips and tricks

Register for shutdown

Function executed at script shutdown

Correct closing of resources

More convenient than ignore_user_abort() a library

In OOP, better use __destruct()

Storing calculated variables

Page 29: PHP tips and tricks

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 30: PHP tips and tricks

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 31: PHP tips and tricks

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 32: PHP tips and tricks

Debugging

get_memory_usage()

memory_limit is now on by default

Better memory handling

The fake growth of memory needs

get_peak_memory_usage()

Page 33: PHP tips and tricks

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 34: PHP tips and tricks

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 36: PHP tips and tricks

Everyone loves PHP