What's New in PHP 5.4
 

What's New in PHP 5.4

on

  • 13,771 views

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, ...

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.

Statistics

Views

Total Views
13,771
Views on SlideShare
13,557
Embed Views
214

Actions

Likes
10
Downloads
167
Comments
3

9 Embeds 214

http://www.redditmedia.com 98
http://www.mikestowe.com 37
http://www.jefersonperito.com 29
http://localhost 20
http://magic-software.ro 14
http://www.linkedin.com 10
https://twitter.com 3
https://www.linkedin.com 2
http://wonder-tonic.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • 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:

    session_start();
    include ('con.php');
    // username and password sent from form
    $myusername=$_POST['myusername'];
    $mypassword=$_POST['mypassword'];
    // 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'';
    $result=mysql_query($sql);

    // Mysql_num_row is counting table row
    $count=mysql_num_rows($result);

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

    if($count==1){

    // Register $myusername, $mypassword and redirect to file 'login_success.php'
    session_register('myusername');
    session_register('mypassword');
    header('location:login_success.php');
    }
    else {
    header('location:index.php');
    }
    .

    Can anyone asset me please,
    Are you sure you want to
    Your message goes here
    Processing…
  • 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
    Your message goes here
    Processing…
  • This is very nice and awesome. thanks for sharing Michael.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • MyProperty;echo' ';$this->MyMethod(); }} (new MyClass())->DoStuff();// echos out 'hello world'?>
  • MyProperty;echo' ';$this->MyMethod(); }} (new MyClass())->DoStuff();// echos out 'hello world'?>
  • MyProperty;echo' ';$this->MyMethod(); }} (new MyClass())->DoStuff();// echos out 'hello world'?>

What's New in PHP 5.4 What's New in PHP 5.4 Presentation Transcript

  • PHP 5.4What’s New and What’s Changedmichael stowe APRIL 7, 2012
  • 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 CaringBridge.org (half a million visitors every day)• Zend Certified PHP 5.3 Software Engineer@mikegstowe
  • THE MOSTIMPORTANT CHANGE
  • The 3 in 5.3 became a 4! (very important)
  • BUT WHAT WILLPHP 5.4 BREAK?
  • 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
  • Reserved KeywordsIn PHP 5.4, the following keywords are nowreserved and cannot be used as function or classnames: • trait • callable • insteadof
  • 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
  • Bye-Bye ExtensionsIn PHP 5.4, the following extension has beenremoved: • sqlite
  • Changed ExtensionsOther important changes: • mysqli_result() now implements Traversable • pdo_mysql no longer supports MySQL < 4.1 • mysqlnd has had named pipes support added
  • 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
  • NOW FOR THE JUICY STUFF
  • 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 “”).
  • 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()
  • 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)
  • 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
  • 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.
  • 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.
  • 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];
  • 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];
  • 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];
  • 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];
  • 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.
  • 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 ?>
  • 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
  • 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?>
  • 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:http://php.net/manual/en/language.oop5.traits.php
  • 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:http://php.net/manual/en/class.reflectionclass.php
  • 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‟);
  • 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‟);
  • SESSIONSPHP 5.4 introduces four new Session items;session_status(), session_register_shutdown(),SessionHandler, and Session based file uploadtracking.
  • 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.
  • 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.
  • 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.
  • 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()
  • 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()
  • 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 **/ }}?> http://www.php.net/manual/en/class.sessionhandler.phpAn instance of this class, a class that extends it, or acustom class implementing the SessionHandlerInterfacewill be passed to session_set_save_handler()
  • 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
  • FILE UPLOAD TRACKINGFile Upload Tracking INI Directives: • session.upload_progress.enabled • session.upload_progress.cleanup • session.upload_progress.prefix • session.upload_progress.name • 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
  • 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("session.upload_progress.name"); ?>"> <input type="file" name="userfile"><br> <input type="submit" value="Start Upload"></form>
  • 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}?>
  • 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:http://phpmaster.com/tracking-upload-progress-with-php-and-javascript/
  • 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
  • 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
  • AND I ALMOST FORGOT…
  • FASTER!
  • PHP Performance252015 PHP 5.410 PHP 5.3 5 PHP 5.3 0 PHP 5.4 bench.php micro_bench.php
  • PHP Performance12001000 800 600 400 PHP 5.4 200 PHP 5.3 0 PHP 5.3 PHP 5.4
  • PHP Performance800060004000 PHP 5.4 PHP 5.32000 PHP 5.3 0 PHP 5.4 blog drupal zf
  • Want to seesomething really cool?
  • RELEASED3.1.2012
  • To read that tiny text and see all the changes http://php.net/ChangeLog-5.php@mikegstowe