Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

What's New in PHP 5.4


Published on

A quick overview of some of the changes and new features in PHP 5.4 including binary notation, short-hand arrays, dereferencing arrays, traits, class instantiation chaining, session_status, sessionHandler, session file upload tracking, and the new built in web server.

Published in: Technology
  • in the previous version of PHP I was using SESSION_START( ); in login-form loading page, there were no problem, it was working properly, but now with the PHP 5.4.8 its not supporting(not loading the page which comes after login-form) for e.g:

    include ('con.php');
    // username and password sent from form
    // To protect MySQL injection (more detail about MySQL injection)
    $myusername = stripslashes($myusername);
    $mypassword = stripslashes($mypassword);
    $myusername = mysql_real_escape_string($myusername);
    $mypassword = mysql_real_escape_string($mypassword);

    $sql='SELECT * FROM members WHERE username='$myusername' and password='$mypassword'';

    // Mysql_num_row is counting table row

    // If result matched $myusername and $mypassword, table row must be 1 row


    // Register $myusername, $mypassword and redirect to file 'login_success.php'
    else {

    Can anyone asset me please,
    Are you sure you want to  Yes  No
    Your message goes here
  • Thanks Mak! Just a couple corrections:
    - break and continue are statements and not functions, so disregard the parenthesis following them.

    - http_response_codes should be http_response_code (singular)

    - And zend.multibyte support is actually 'off' by default
    Are you sure you want to  Yes  No
    Your message goes here
  • This is very nice and awesome. thanks for sharing Michael.
    Are you sure you want to  Yes  No
    Your message goes here

What's New in PHP 5.4

  1. 1. PHP 5.4What’s New and What’s Changedmichael stowe APRIL 7, 2012
  2. 2. MIKESTOWE .com• 10+ years experience hacking PHP• Developed web applications for large non-profits, the medical field, law enforcement, and ecommerce websites• Open Source Contributor (3 WordPress plugins, multiple scripts)• Software Engineer at (half a million visitors every day)• Zend Certified PHP 5.3 Software Engineer@mikegstowe
  4. 4. The 3 in 5.3 became a 4! (very important)
  6. 6. Well for starters…• break and continue no longer accept variablearguments• safe_mode is no longer supported• Salsa10/20 algorithms have been removed• Magic Quotes• (object) null now throws a warning• (string) array() now throws an E_NOTICE• Shadowing SuperGlobals as parameter names nowcauses fatal error
  7. 7. Reserved KeywordsIn PHP 5.4, the following keywords are nowreserved and cannot be used as function or classnames: • trait • callable • insteadof
  8. 8. Bye-Bye FunctionsIn PHP 5.4, the following functions have beenremoved:• define_syslog_variables• import_request_variables• session_is_registered• session_register• session_unregister• mysqli_bind_param• mysqli_bind_result• mysqli_fetch
  9. 9. Bye-Bye ExtensionsIn PHP 5.4, the following extension has beenremoved: • sqlite
  10. 10. Changed ExtensionsOther important changes: • mysqli_result() now implements Traversable • pdo_mysql no longer supports MySQL < 4.1 • mysqlnd has had named pipes support added
  11. 11. INI RemovalsOther important changes: • register_globals and register_long_arrays have been removed!!! (it’s about time!) • safe_mode and all related components removed • y2k_compliance removed • Zend.ze1_compatibility_mode removed
  13. 13. PHP 5.4 INI STUFFPHP 5.4 comes with the following new ini directives: • cli.pager and cli.prompt for CLI SAPI using readline in interactive mode • zend.multibyte to control new multibyte support (off by default) • session.upload directives • enable_post_data_reading to stop POST data from being read and processed (when disabled) • default_charset is now UTF-8 in distributed php ini files (still defaults to “”).
  14. 14. New FunctionsHere are some of the brand new functions! • hex2bin() • http_response_code() • get_declared_traits() • getimagesizefromstring() • stream_set_chunk_size() • socket_import_stream() • trait_exists() • header_register_callback()
  15. 15. New Functions (cont)Here are some of the brand new functions! • class_uses() • session_status() • session_register_shutdown() • mysqli_error_list() • mysqli_stmt_error_list() • and others (Libxml, LDAP, Intl)
  16. 16. New Features in 5.4And the big ticket items in PHP 5.4 include: • Binary Notation • Short-hand arrays • Dereferencing arrays • Traits • Class Instantiation Chaining • Session Status and Handler • File Upload Tracking • Built in Web Server
  17. 17. BINARY NOTATIONPreviously in PHP, you were able to writeintegers as decimals (10), Octals (012), andHexadecimals (0xA). Now in PHP 5.4 you canuse binary notation for integers by preceding thebinary number with “0b” – such as (0b1010).That‟s zero-lower-case-bfollowed by the binary.
  18. 18. Binary is calculated byExample Usage using the powers of 2. IE 20, 21, 22, 23, etc. So 100101 would be equal to:<?php [(1) × 25] + [(0) × 24] + [(0) ×// Decimal 23] + [(1) × 22] + [(0) × 21] +echo (string) 10; // 10 [(1) × 20]// Octalecho (string) 012; // 10// Hexadecimalecho (string) 0xA; // 10// Binaryecho (string) 0b1010; // 10?> That‟s zero-lower-case-b followed by the binary.
  19. 19. SHORT-HAND ARRAYSFinally, in PHP you can now use the short bracketsyntax for arrays. While really not a huge deal, thisaligns PHP with many of the other programminglanguages, and will probably make switching fromanother language just a little easier (althougharray(1,2,3) is pretty simple).$array = array(1,2,3);$array = [1,2,3];
  20. 20. Example Usage <?php $oldArray = array(1,2,3); echo (string) $oldArray[1]; // 2 $newArray = [1,2,3]; echo (string) $newArray[1]; // 2 $newArray = [1 => Apple, 2, 3]; echo (string) $newArray[1]; // Apple $newArray = [apple => Orange]; echo $newArray[apple]; // Orange ?>You can have values OR key => value pairs! $array = array(1,2,3); $array = [1,2,3];
  21. 21. DEREFERENCINGARRAYSAnother nice feature in regards to arrays isArray Dereferencing, or being able toaccess an array object directly off of amethod or function.echo functionReturningAnArray()[1];
  22. 22. Example Usage<?phpfunction getArray(){ return array(1,2,3); // or return [1,2,3]; short syntax ;)}// PHP 5.3echo (string) getArray()[1]; // error// PHP 5.4echo (string) getArray()[1]; // 2?> This works for functions and methods echo functionReturningAnArray()[1];
  23. 23. TRAITSThe addition of traits provides the flexibility of“extending” multiple classes without having to gothrough an entire chain (allowing horizontaldesign). Unlike many languages, PHP Traits can alsocontain properties, however, if the class contains aproperty with the same name it will throw an E_STRICTwarning IF the class property === the trait property, ora fatal error if the class property !== the trait property.Traits are interchangeable classes that can beimported into a class through the “use” declaration.
  24. 24. Example Usage <?php trait MyTrait { public $MyProperty = hello; public function MyMethod() { echo world; } } class MyClass { use MyTrait; public function DoStuff() { echo $this->MyProperty; echo ; $this->MyMethod(); } } (new MyClass())->DoStuff(); // echos out hello world ?>
  25. 25. Using Multiple Traits <?php class MyClass { use MyTrait, YourTrait // Assuming both traits have // exampleMethod() this will as allows us to still // cause a conflict, unless we access MyTrait’s // tell it not to... { exampleMethod // Alias for MyTraits method MyTrait::exampleMethod as example1; // Use YourTrait instead of MyTrait YourTrait::exampleMethod insteadof MyTrait; } } We have to use $myClass = new MyClass(); insteadof to // MyTrait::exampleMethod avoid a conflict $myClass->example1(); // YourTrait::exampleMethod $myClass->exampleMethod(); ?>To avoid method conflicts, you can create aliasesusing as AND tell PHP which trait‟s method to useinsteadof another trait‟s identically named method
  26. 26. Class Overrides<?phptrait MyTrait{ public function MyMethod() We can still access { MyTrait::MyMethod echo MyTrait; } by creating an alias} as shown in theclass MyClass{ last slide use MyTrait; public function MyMethod() { echo MyClass; } public function DoStuff() { $this->MyMethod(); }}(new MyClass())->DoStuff(); // echos out MyClass?>
  27. 27. Trait Functionstrait_exists() – similar to class_exists(), this function checksto see if the trait has been defined and returns anboolean.get_declared_traits() – similar to get_declared_classes(), thisfunction returns an array of traits that have beendeclared.For more on traits visit:
  28. 28. Traits & the Reflection ClassThere have also been several methods added to the ReflectionClass:getTraits() returns an array of all traits used in a class, whilegetTraitNames() returns an array of the trait names in a class.getTraitAliases() returns an array of aliases linked to its original traitand method.isTrait() returns whether or not a tested object is a traitFor more on the ReflectionClass visit:
  29. 29. CLASS INSTANTIATIONCHAININGAs you may have noticed by the Traits codeexample, PHP 5.4 let’s you chain a classinstantiation using parenthesis.This allows you to instantiate a class, and call amethod all in one act.(new ClassName())->classMethod(„param1‟);
  30. 30. Example Usage<?phpclass Test{ public function hello() { echo hello world; }}// in PHP 5.3 this would be an error// in PHP 5.4 it echos hello worldecho (new Test())->hello();?>Keep in mind that just because you can dosomething doesn’t mean you should. Stick tocoding standards.(new ClassName())->classMethod(„param1‟);
  31. 31. SESSIONSPHP 5.4 introduces four new Session items;session_status(), session_register_shutdown(),SessionHandler, and Session based file uploadtracking.
  32. 32. SESSION_STATUSsession_status() returns the CURRENT statusof the session, whether sessions aredisabled, if there is an active session, or ifthere are no active sessions. Let’s take a look at it in action…session_status() allows you to see the session‟sstatus in real time instead of checking theSuperGlobal and headers.
  33. 33. Example Usage <?php //If sessions are disabled //would return PHP_SESSION_DISABLED (0) echo session_status(); // echos PHP_SESSION_NONE (1) session_start(); echo session_status(); // echos PHP_SESSION_ACTIVE (2) session_destroy(); echo session_status(); // echos PHP_SESSION_NONE (1) ?>session_status() allows you to see the session‟s status inreal time instead of checking the SuperGlobal andheaders.
  34. 34. SESSION_REGISTER_SHUTDOWN session_register_shutdown() registers session_write_close() as a shutdown function. <?php session_start(); session_register_shutdown(); ?>It‟s important to remember that all the othersession_register functions have been deprecated.
  35. 35. SESSIONHANDLER SessionHandler is a class introduced in PHP 5.4 to help make building custom session handlers easier. The SessionHandler class implements the SessionHandlerInterface, which may be independently called in by a custom class.An instance of this class, a class that extends it, or acustom class implementing the SessionHandlerInterfacewill be passed to session_set_save_handler()
  36. 36. SESSIONHANDLER SessionHandler methods include: • close() – executed on the close of the session • destroy() – executed when destroying a session • gc() – cleans up expired sessions • open() – when opening or creating a session • read() – executed after session_start() • write() – executed by session_write_close()An instance of this class, a class that extends it, or acustom class implementing the SessionHandlerInterfacewill be passed to session_set_save_handler()
  37. 37. Example Usage<?phpclass MyHandler extends SessionHandler{ public function read($session_id) { /** GET SESSION DATA FROM YOUR SOURCE **/ } public function write($session_id, $session_data) { /** WRITE SESSION DATA TO YOUR SOURCE **/ }}?> instance of this class, a class that extends it, or acustom class implementing the SessionHandlerInterfacewill be passed to session_set_save_handler()
  38. 38. FILE UPLOAD TRACKINGFile upload tracking allows you to track theprogress of a file upload through sessions. This is done only using PHP and JavaScript!File upload tracking is setup through thesession.upload_progress ini directives,and then stored in the $_SESSION SuperGlobal
  39. 39. FILE UPLOAD TRACKINGFile Upload Tracking INI Directives: • session.upload_progress.enabled • session.upload_progress.cleanup • session.upload_progress.prefix • • session.upload_progress.freq • session.upload_progress.min_freqFile upload tracking is setup through thesession.upload_progress ini directives,and then stored in the $_SESSION SuperGlobal
  40. 40. FILE UPLOADTRACKINGAfter setting the appropriate inidirectives, you will need to setupyour upload form:<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" id="myForm" enctype="multipart/form-data"> <input type="hidden" value="myForm" name="<?php echo ini_get(""); ?>"> <input type="file" name="userfile"><br> <input type="submit" value="Start Upload"></form>
  41. 41. FILE UPLOADTRACKINGYou can then access the file uploadprogress data from the session:<?phpsession_start();$key = ini_get("session.upload_progress.prefix") . "myForm";if (!empty($_SESSION[$key])) { $current = $_SESSION[$key]["bytes_processed"]; $total = $_SESSION[$key]["content_length"]; echo $current < $total ? ceil($current / $total * 100) : 100;}else { echo 100; // File has been Completely Uploaded}?>
  42. 42. FILE UPLOAD TRACKING With the previous PHP script we can return the upload progress in a percentage back to the original form via ajax. Mix in a little CSS to make it look even better!See more code and learn how tomake the above example at PHP Master:
  43. 43. BUILT-IN WEBSERVERPHP 5.4 also comes with a built-inwebserver via the command line forconvenience$ cd ~/public_html$ php -S localhost:8000The server is activated using the –S option Note: the webserver is for development purposes only, and should not be used in production
  44. 44. Example Usage $ cd ~/public_html $ php -S localhost:8000 router.phpWould return something like PHP 5.4.0 Development Server started at Thu Jul 21 10:53:19 2011 Listening on localhost:8000 Document root is /home/me/public_html Press Ctrl-C to quit. [Thu Jul 21 10:53:45 2011] ::1:55801 GET /mylogo.jpg - Request read [Thu Jul 21 10:53:52 2011] ::1:55803 GET /abc.html - Request read [Thu Jul 21 10:53:52 2011] ::1:55804 GET /favicon.ico - Request read Note: the webserver is for development purposes only, and should not be used in production
  46. 46. FASTER!
  47. 47. PHP Performance252015 PHP 5.410 PHP 5.3 5 PHP 5.3 0 PHP 5.4 bench.php micro_bench.php
  48. 48. PHP Performance12001000 800 600 400 PHP 5.4 200 PHP 5.3 0 PHP 5.3 PHP 5.4
  49. 49. PHP Performance800060004000 PHP 5.4 PHP 5.32000 PHP 5.3 0 PHP 5.4 blog drupal zf
  50. 50. Want to seesomething really cool?
  51. 51. RELEASED3.1.2012
  52. 52. To read that tiny text and see all the changes