PHP Tips & Tricks

  • View
    15.166

  • Download
    2

Embed Size (px)

DESCRIPTION

Tips and tricks about PHP - some rechniques, not well known functions etc.

Text of PHP Tips & Tricks

  • 1.PHP TIPS & TRICKS1

2. PHP TIPS & TRICKS AKAJOURNEY INTO DEPTHS OF MANUAL 2 3. name: Radosaw Benkelnick: singleswww: http://www.rbenkel.metwitter: @singlespl ** and I have nothing in common with http://www.singles.pl ;] 3 4. DEVELOPERS OFFEN WRITE FUNCTIONS FORSOMETHING, THAT ALREADY EXISTS. 4 5. WHY? 5 6. WHY?SOMETIMES THEY WANT TO DO SOMETHING BETTER.6 7. WHY?SOMETIMES THEY WANT TO DO SOMETHING BETTER.OR JUST DONT KNOW THAT SOMETHING ALREADY EXISTS. 7 8. SOME OF THESE YOU MAY KNOW.8 9. SOME OF THESE YOU MAY KNOW.SOME DONT.9 10. SOME OF THESE YOU MAYKNOW.SOME DONT.IF YOU KNOW BETTERSOLUTION, PLEASE SHARE :)10 11. SHORT TERNARYOPERATOR11 12. SHORT TERNARY OPERATOR$var = SomeValue;$output = $var ? $var : default;$output = $var ?: default; //PHP >= 5.312 13. DIRECTORY LISTING13 14. DIRECTORY LISTING #1$dir = "/application/modules/*";if (is_dir($dir)) {if ($dh = opendir($dir)) {while (($file = readdir($dh)) !== false) {echo "Filename is: " . $file . PHP_EOL;}closedir($dh);}} 14 15. DIRECTORY LISTING #2$dir = "/application/modules/*";foreach(glob($dir) as $file) {echo "Filename is: " . $file . PHP_EOL;} 15 16. DIRECTORY LISTING #3$dir = "/application/modules/";foreach (new DirectoryIterator($dir) as $fileInfo) {echo "Filename is: " . $fileInfo->getFilename() . PHP_EOL;}16 17. DIRECTORY LISTING #3$dir = "/application/modules/";foreach (new DirectoryIterator($dir) as $fileInfo) {echo "Filename is: " . $fileInfo->getFilename() . PHP_EOL;} andlotofothers:http://www.php.net/manual/en/class.directoryiterator.php17 18. EXPLODED STRING VALUES18 19. EXPLODED STRING VALUES$string = bazinga.foo.bar.suitup!$values = explode(., $string);$sheldon= $values[0]; //bazinga$barney = $values[3]: //suituplist($sheldon, , , $barney) = explode(., $string);//PHP 5.4 stuff$sheldon = explode(., $string)[0];$barney = explode(., $string)[3]; 19 20. FILEPATH INFORMATION 20 21. FILEPATH INFORMATION$path = /some/directory/in/filesystem/file.some.txt;$parts = explode(/, $path);$partsCopy = $parts;array_pop($partsCopy);// /some/directory/in/filesystem$filePath = implode(/, $partsCopy);$fileExtension = explode(., $parts[count($parts) - 1]);// txt$fileExtension = $fileExtension[count($fileExtension)-1]; 21 22. FILEPATH INFORMATION Butwhy? 22 23. FILEPATH INFORMATION$path = /some/directory/in/filesystem/file.some.txt;$fileInfo = pathinfo($path);$fileInfo[dirname]=== pathinfo($path, PATHINFO_DIRNAME);$fileinfo[basename] === pathinfo($path, PATHINFO_BASENAME);$fileinfo[extension] === pathinfo($path,PATHINFO_EXTENSION);$fileinfo[filename] === pathinfo($path, PATHINFO_FILENAME);23 24. FIRST NOT EMPTY VARIABLE 24 25. FIRST NOT EMPTY VARIABLEAKACOALESCE, NVL 25 26. FIRST NOT EMPTY VARIABLE$a = null;$b = false;$c = 14;$d = foo;$notEmpty = $a ?: $b ?: $c ?: $d;echo $notEmpty // 1426 27. DEEP VAR INTERPOLATION27 28. DEEP VAR INTERPOLATION$obj = new stdClass();$obj-some = hello;$obj-foo = new stdClass();$obj-foo-bar = 123;echo Value is $obj-some;//Object of class stdClass could not be converted to string inecho Value is $obj-foo-bar;//Value is 123echo Value is {$obj-foo-bar};//Same for array$ar = array(some = var);echo Value is $ar[some]; //syntax errorecho Value is {$ar[some]}; //Value is var28 29. MULTIPLE ISSET29 30. MULTIPLE ISSET$val = null;$var = true;if (isset($not_defined)isset($val)isset($var)) {/* ... */} 30 31. MULTIPLE ISSETif (isset($not_defined)isset($val)isset($var)) {/* ... */}===if (isset($not_defined, $val, $var)) {/* ... */} 31 32. FILTER_INPUT 32 33. FILTER_INPUT$action = isset($_POST[action])? some_validate($_POST[action]): default_action; 33 34. FILTER_INPUT 34 35. FILTER_INPUT/* data actually came from POST$_POST = array(product_id= libgdscript,component = 10,versions= 2.0.33,testscalar= array(2, 23, 10, 12),testarray = 2,);*/$args = array(product_id = FILTER_SANITIZE_ENCODED,component= array(filter= FILTER_VALIDATE_INT,flags = FILTER_REQUIRE_ARRAY,options = array(min_range = 1, max_range = 10)),versions = FILTER_SANITIZE_ENCODED,doesnotexist = FILTER_VALIDATE_INT,testscalar = array(filter = FILTER_VALIDATE_INT,flags = FILTER_REQUIRE_SCALAR,),testarray= array(filter = FILTER_VALIDATE_INT,flags = FILTER_REQUIRE_ARRAY,));$myinputs = filter_input_array(INPUT_POST, $args); 35 36. STRING CONCATENATION 36 37. STRING CONCATENATIONTIME F OR R IDDLE! 37 38. STRING CONCATENATION WHO K NOWS W HATS T HAT? 38 39. STRING CONCATENATION WHO K NOWS W HATS T HAT?39 40. STRING CONCATENATION CORRECT! 40 41. STRING CONCATENATION 41 42. STRING CONCATENATION$a = scissors;$b = paper;$c = rock;$d = lizard;$e = Spock;$rules = $a .cut. $b . ,. $b .covers.$c . ,. $c .crushes. $d . ,. $d . poisons. $e . ...;echo $rules;//scissors cut paper, paper covers rock, rock crusheslizard, lizard poisons Spock... 42 43. STRING CONCATENATION$a = scissors;$b = paper;$c = rock;$d = lizard;$e = Spock;$rules = $a cut $b, $b covers $c, $c crushes $d, $dpoisons $e...;echo $rules;//scissors cut paper, paper covers rock, rock crusheslizard, lizard poisons Spock... 43 44. STRING CONCATENATION$a = scissors;$b = paper;$c = rock;$d = lizard;$e = Spock;$rules = %s cut %s, %s covers %s, %s crushes %s, %s poisons %s...;echo sprintf($rules, $a, $b, $b, $c, $c, $d, $d, $e);echo vsprintf($rules, array($a, $b, $b, $c, $c, $d, $d, $e));printf($rules, $a, $b, $b, $c, $c, $d, $d, $e);vprintf($rules, array($a, $b, $b, $c, $c, $d, $d, $e));//4x scissors cut paper, paper covers rock, rock crushes lizard, lizardpoisons Spock...44 45. STRING CONCATENATIONWHY U SE P RINTF FAMILY F UNCTIONS,WHEN W E H AVE S TRINGINTERPOLATION? 45 46. STRING CONCATENATION STRING PATTERN REUSE(CONNECTION STRINGS, API CALLS, ETC.)46 47. STRING CONCATENATION LOT OF FORMATTING OPTIONS47 48. QUICK OBJECT DEFINITION 48 49. QUICK OBJECT DEFINITION$obj = new stdClass();$obj-foo = 123;$obj-bar = some;//or (btw. not recursive!)$obj = (object)array(foo = 123, bar = some);// unfortunately - not possible :($obj = {foo = 123} 49 50. ENUM 50 51. ENUMclass Roles {const ADMIN = 1;const USER= 2;const GUEST = 3;}$class = new ReflectionClass(Roles);var_dump($class-getConstants());/*array(3) { [ADMIN]= int(1) [USER]= int(2) [GUEST]= int(3)}*/51 52. SPL FTW! 52 53. DATE/TIME MANIPULATION53 54. DATE/TIME MANIPULATION54 55. DATE/TIME MANIPULATION+ OBJECT/PROCEDURAL+ TIMEZONES+ INTERVALS+ SOME OPERATORS+ PHP CORE SINCE 5.2 55 56. DATE/TIME MANIPULATION$a = new DateTime(2011-12-12);$b = new DateTime(2011-11-12);$c = new DateTime(2011-12-12);var_dump(($a$b)); // falsevar_dump(($a$b)); // truevar_dump(($c == $a)); // true// works$a-add(new DateInterval(P2D));echo $a-format(Y-m-d) // echo 2011-12-14// dont work :($a += new DateInterval(P2D); 56 57. DID YOU MEAN ...57 58. DID YOU MEAN ...58 59. DID YOU MEAN ...YOU CAN TRY:http://php.net/manual/en/function.levenshtein.php59 60. PARSING URL PARAMS60 61. PARSING URL PARAMSparse_url + parse_str61 62. PARSING URL PARAMSparse_url$url = http://username:password@hostname/path?arg=value#anchor;print_r(parse_url($url));echo parse_url($url, PHP_URL_PATH); //and others, same as pathinfo/*Array([scheme] = http[host] = hostname[user] = username[pass] = password[path] = /path[query] = arg=value[fragment] = anchor)/path*/62 63. PARSING URL PARAMSparse_strparse_str(single=Singlecheck[]=check1check[]=fooradio=radio2, $data);print_r($data);die();/*Array([single] = Single[check] = Array([0] = check1[1] = foo) [radio] = radio2)*/63 64. PARSING URL PARAMSparse_strparse_str(single=Singlecheck[]=check1check[]=fooradio=radio2, $data);print_r($data);die();/*Array([single] = Single[check] = Array([0] = check1[1] = foo) DOntusewithoutsecondparameter! [radio] = radio2)*/ 64 65. PARSING URL PARAMSparse_strfunction foo() {parse_str(single=Singlecheck[]=check1check[]=fooradio=radio2);print_r(get_defined_vars());die();}foo(); Localmagicvariables! 65 66. CSV PARSING 66 67. CSV PARSINGfgetcsv + str_getcsv 67 68. CSV PARSING fgetcsv (for big files)$row = 1;if (($handle = fopen(test.csv, r)) !== FALSE) {while (($data = fgetcsv($handle, 1000, ,)) !== FALSE) {$num = count($data);echo p $num fields in line $row: br //pn;$row++;for ($c=0; $c$num; $c++) {echo $data[$c] . br /n;}}fclose($handle);}?68 69. CSV PARSINGstr_getcsv (for smaller ones)$line = AddDescription My description to the file.filename.jpg;$parsed = str_getcsv($line, # Input line , # Delimiter, # Enclosure # Escape char);var_dump( $parsed ); 69 70. AUTO_PREPEND_FILE70 71. AUTO_PREPEND_FILEphp.iniauto_prepend_file stringSpecifies the name of a file that is automatically parsed before themain file. The file is included as if it was called with therequire()function, so include_path is used.The special value none disables auto-prepending. 71 72. AUTO_PREPEND_FILE php.iniauto_prepend_file stringSpecifies the name of a file that is automatically parsed before themain file. The file is included as if it was called with therequire()function, so include_path is used.The special value none disables auto-prepending. Greatplaceforyourawesomemydie,dump,debug,pukeetc.functions.Butbecarefulwhendeploying. 72 73. FILE INCLUDE 73 74. FILE INCLUDE//config.php$dbName = some;$dbPass = foo;$dpPort = 123;//index.phpinclude config.php;echo $dbPass; //echo some74 75. FILE INCLUDE//config.php$dbName = some;$dbPass = foo;$dpPort = 123; magicvariable! Local//index.phpinclude config.php;echo $dbPass; //echo some 75 76. FILE INCLUDE//config.phpreturn array(dbName = some,dbPass = foo,dbPort = 123);//index.php$config = include config.php;echo $dbPass; //Notice undefinedecho $config[dbName] = some; 76 77. FILE INCLUDEBTW. T HIS A LSO W ORKS//function.phpreturn function($data) {print_r($data);die();};//index.php$dump = include function.php;$dump(array(hello, moto));77 78. QUICK COMMENT WITHOUT IDE78 79. QUICK COMMENTfunction foo() {$items = array();foreach (array(some, a) as $item) {if ($item === a) {continue;}$items[] = $item;}return $items;} 79 80. QUICK COMMENTfunction foo() {$items = array();/*foreach (array(some, a) as $item) {if ($item === a) {continue;}$items[] = $