navigate site menu

Start learning with our library of video tutorials taught by experts. Get started

PHP 5.5 First Look

PHP 5.5 First Look

with Jon Peck

 


Join author Jon Peck as he demonstrates new functionality in PHP 5.5, including generators, the try-catch-finally execution model, and a brand-new password hashing API. A number of existing behaviors, such as the foreach() and empty() functions, have also been updated, and Jon explores what changed and how it can be used. Throughout this course, you'll learn to add new functionality to a simple deck of cards class using these new and updated features, and how to use them for the basis of your own project.
Topics include:
  • Using generators to create simple iterators
  • Dereferencing strings and arrays
  • Enhancing security with the password hashing API
  • Replacing APC with OPcache
  • Normalizing Boolean and unpack() behavior
  • Surveying the removed, incompatible, and deprecated functionality

show more

author
Jon Peck
subject
Developer, Servers, Programming Languages
software
PHP 5.5
level
Intermediate
duration
42m 29s
released
Jun 14, 2013

Share this course

Ready to join? get started


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:00 (music playing)
00:04 Hi, I'm Jon Peck, and welcome to PHP 5.5 First Look.
00:09 In this course, we'll explore the new functionality and changes in the latest
00:12 version of PHP. I'll start with new features in PHP
00:15 including the password hash in API and the new op cache.
00:20 Throughout this course, we'll develop practical examples using a deck of common
00:23 playing cards that will exercise PHP's new and updated features.
00:28 We'll even perform some bench marking to compare the speed differences between
00:31 major versions. Which will be particularly helpful when
00:34 determining whether or not it's worth it to upgrade.
00:37 Let's get started.
00:38
Collapse this transcript
Exercise files
00:00 In this course, I'm going to be developing in a sandbox PHP environment,
00:04 using PHP 5.5 as the server-side language.
00:07 Only this major version will be covered for obvious reasons.
00:12 I'll also be using MySQL 5.5 for the database for some of the benchmarking and
00:16 demonstrations, and Apache 2 as the web server.
00:19 Other web servers such as nginx and IIS will not be covered in this course, but
00:24 they should work. If you don't already have a server for
00:27 development I recommend using a local development server running on your work station.
00:32 In this course I'm going to nee demonstrating using a virtualized server
00:35 running in my existing operating system. If you'd like a server configured using
00:39 this technique check out Up And Running with Linux for PHP developers here in the
00:44 lynda.com online training library. As part of this course, I'll show how to
00:49 configure that server to work with PHP 5.5.
00:53 Regardless of the location of your web server, you're going to need access to
00:56 the command line with administrative credentials in order to install and
00:59 configure server software. For Mac and Linux, the terminal allows
01:03 you to access the command line which includes access to the SSH command if the
01:08 site is hosted remotely. For Windows you can use the free program
01:12 PuTTY to connect via ssh remote servers available form the official PuTTY website.
01:17 I'll demonstrate writing code using NetBeans 7.3 IDE bundle for php.
01:22 NetBeans is a free open source and cross platform integrated development
01:27 environment from NetBeans.org. The goal of the course is to demonstrate
01:31 what's new in PHP 5.5, not how to use netbeans, but with that said, I'm only
01:36 going to be editing code in NetBeans. Any IDE or text editor will work.
01:41 I will warn you in advance, that NetBean does not understand PHP 5.5 new
01:45 functionality, and as such will mark PHP 5.5 code as errors.
01:51 The exercise files for this course are contained in folders by chapter and movie.
01:56 On my work station I have them in a folder named sandbox that my virtualized
01:59 Linus server can access. Depending on your web server
02:03 configuration you may need to store these files in a different place such as a
02:07 remote web server or in a folder accessible by a local Apache and PHP stack.
02:12 Be sure to import the included SQL, and copy the contents of the folder named
02:16 Cards to your web root. A final note.
02:20 As different web hosts and configurations serve content from different URLs, the
02:24 address you see in my browser may not exactly match what you see on your workstation.
02:29 Additionally, the locations shown in the command prompt demonstrations will differ
02:33 depending on the location of site files and configurations on your server.
02:37 The software configuration will be very similar, if not identical across platforms.
02:41
Collapse this transcript
What you should know
00:00 Before starting this course, you should have a basic knowledge of the PHP
00:03 language and have written a few scripts. Without this background, you might not
00:07 have enough context to understand the significance or utility of the new
00:10 features, which can be frustrating. For some background or a refresher, I
00:15 recommend PHP with MySQL Essential Training with Kevin Skoglund, here in the
00:20 lynda.com online training library. If you're unfamiliar with configuring web
00:25 server components, check out the course Installing Apache, MySQL, and PHP with
00:29 David Gassner, here in the lynda.com online training library for a
00:33 comprehensive perspective on how to best manage the solution stack.
00:36
Collapse this transcript
Building a virtual PHP 5.5 development environment
00:00 This course is on PHP 5.5, but finding a host or server stack that already has it
00:04 installed might be difficult, especially in the context that it took almost 4
00:08 years from June 2009 to March 2013 for PHP 5.3 to surpass 5.2 as the most
00:12 installed version. Therefore, I'm going to install PHP 5.5
00:19 on a local virtual server from up and running with Linux for PHP developers.
00:25 All that's needed is to complete the steps from Chapter 3 and Chapter 4.
00:29 Use of this environment is not required for this course, but it's good to know
00:32 that there's an option. If you're not interested, just skip
00:35 forward to Chapter 1. I'm going to be using Virtual Box 4.2.12
00:41 from virtualbox.org and Ubuntu Server 12.04.2 long-term support 64-bit from ubuntu.com.
00:50 To make it easy to install PHP 5.5, I'm going to use phpbrew, which quickly
00:54 compiles specific versions of PHP. phpbrew can be found at github.com.
01:02 I'm going to configure Apache to use PHP 5.5 as the default.
01:07 I'm going to go to a terminal, and then, SSH into my server environment, so for
01:11 me, it'll be ssh sandbox. The first thing I'm going to do is start
01:17 an interactive sudo session, which means every commands that I'm going to give
01:21 will be its root. So I'll type sudo su, it'll ask me for my
01:26 password, and I'm in. I'm going to install the prerequisites
01:32 for PHP 5.5, apt-get -y install autoconf automake curl build-essential
01:39 Libxslt1-dev re2c libxml2-dev, and finally, libmcrypt-dev.
01:49 Now that those prerequisites are installed, I'm going to install PHP 5's dependencies.
01:59 This is different than installing PHP 5, apt-get dash y build-dep php5.
02:10 This will take a minute or two. Now that the dependencies have been
02:13 built, I'm going to download phpbrew, which will do the actual compilation.
02:19 I'm going to change directory to usr/bin, then I will use the command curl dash
02:27 space O to download the file from https://raw.github.com/c9s/phpbrew/master/phpbrew.
02:39 I'll make phpbrew executable, chmod plus x phpbrew.
02:46 Then, I'll initialize it, phpbrew init. I'm going to specify where versions of
02:53 php will be installed, echo export PHPBEW_ROOT equals/opt/phpbrew.
03:03 I'm going to send that to ~/.phpbrew/init.
03:07 Then, I'll load the phpbrew configuration by default, echo source ~/.php brew/.
03:15 I'll send that to i bashrc. I'll load the new configuration, source ~/.bashrc.
03:28 Now that phpbrew is ready, I'm going to determine all the available versions of
03:34 PHP 5.5 using phpbrew known space dash dash dsp, and I'll pipe that to grep
03:40 space dash i php dash 5,5. At the time of this recording, PHP 55.0
03:48 Release Candidate 1 is the latest version, so I'll use that for this course.
03:57 Now that I know what version is available, I'm going to use phpbrew to
04:02 install it, phpbrew install php dash 5.5.0rc1, and I'll include the default
04:08 variants, database, multibyte, m crypt, apache supported, apxs2 equals user bin, apxs2.
04:19 And then, finally, enable opcache, which I'll demonstrate in a bit.
04:25 phpbrew will now download the source code of PHP and compile it with the options
04:30 I've given. Now that PHP 5.5 has been installed, I'm
04:35 going to use php 5 for this command line session.
04:41 phpbrew use php dash 5.5.0rc1. I'm going to configure the date and error
04:50 log by editing php.ini. nano dash w/opt/phpbrew/php/php-5.5.0rc1/etc/php.ini.
05:02 I'm going to search for date.timezone, I'm going to set it to
05:08 America/Los_Angeles and change error_log. And I'm going to set error_log, equal to
05:22 media sf_sandbox slash php_errors.log. I'll look for session.save path equals,
05:37 and I'm going to uncomment it. I'm going to search for pdo, mysql.default_socket.
05:46 And now that's set to nothing, I'm going to set it to var/run/mysqld/mysqld.sock.
05:55 I will do the same for the mysql.default_socket, var
06:01 run/mysqld/mysqld dot.sock and the mysqli.default_socket var run mysqld/mysqld.sock.
06:14 I'm going to Save, and Exit. I'll reload the Apache configuration to
06:19 take advantage of the new version of PHP, service apache2 reload.
06:24 I'm going to verify from the command line php dash fee.
06:30 Excellent, it's using PHP 55. And I'm going to check for opcache php
06:36 dash i grep opcache. It's been installed, but it hasn't been
06:40 configured yet. I'm going to exit out of the root session
06:44 and set up phpbrew for my regular user as well, phpbrew init.
06:50 I'm going to specify where versions of PHP will be installed, which will be echo
06:56 export PHPBREW_ROOT equals slash opt phpbrew, and I'll send that to phpbrew/init.
07:05 I'll load the configuration by default by echoing source phpbrew dash rc, and I'll
07:12 send that to slash bashrc, and finally I'll source bashrc.
07:19 That's all the configuration that's needed.
07:21 I'm going to switch to my browser now and navigate to the web root, http://sandbox.dev:8080.
07:30 I'll see a status report. The very first one, Database content
07:34 Exists verifies that it's able to connect to the database.
07:38 If not, you'll need to go into the exercise files and edit config.inc.php
07:42 and make the database configuration changes as needed.
07:47 Additionally, it will check various php.ini settings including the
07:51 date.timezone, the mysql.default_sockets, session.save_path, and error_log.
07:57 I can see that opcache.enable and enable_cli are unset.
08:02 That's because I haven't explicitly enabled.
08:04 I will do that later in this course. Click on phpinfo.
08:08 I can see that I'm running PHP 5.5, which means the installation was successful.
08:14 Now that my environment has been configured, let's take a look at what's
08:17 new in PHP 5.5.
08:19
Collapse this transcript
1. New Features in PHP 5.5
Simple iterators using generators
00:00 One of the most common programming needs, is to be able to perform an action on
00:04 every element of an object. For example, using a foreach on an array,
00:08 to get each key in value, or a foreach on a standard object, to get each parameter
00:12 name and value. The mechanism for implementing this
00:16 behavior is known as an iterator, which is used for traversing through all
00:19 elements of an object or an array. Iterators can be explicitly defined for
00:24 custom classes, but that can be an unwieldy and complicated process
00:27 involving implements and, more than a handful of functions.
00:31 What if I want to act on a subset of an array, and perform some logic as I go
00:35 along, but still be able to iterate through the object?
00:37 Well, PHP 5.5 has introduced generators, which are an easy oilerplate free way, of
00:43 implementing an iterator by using the special yield keyword.
00:48 Yield provides a value to codes looping over the generator, and pauses the
00:51 generator function execution. It'll look very similar to return statement.
00:56 I'm going to use a generator to draw cards from a deck.
01:00 I'm going to switch the IDE, navigate to Classes and open Game.php.
01:06 I'm going to code a public function draw cards.
01:12 This function takes one argument, which is the number of cards to draw.
01:15 I'm going to start with some simple logic.
01:17 So if, number of cards not equals intval number of cards, because you can only
01:26 have whole cards, throw new Exception, cannot take partial cards.
01:34 Now that I have that out of the way, I am going to use the number of cards as part
01:38 of a for loop. For count equals 0, count is less then
01:44 the number of cards, and count ++. I'm going to get the cards from the deck,
01:52 so cards equal this. Deck, get cards.
01:59 If there are any, recycle the deck, meaning put the discard in the deck and shuffle.
02:03 So if, empty, cards, this, recycle. At the end of the loop, I'm going to
02:13 yield a drawn card. This means each time it goes through the
02:16 loop, it'll generate a drawn card. Yield, this_deck, draw.
02:24 Save and navigate to the construct above. I'm doing a foreach for the number of
02:29 players and cards per player, and putting each card yielded by the generator in the hand.
02:34 To see this in action, switch to the browser and click on Game.
02:39 The deck, discard, and two players are rendered with their drawn cards.
02:44
Collapse this transcript
Dereferencing strings and arrays
00:00 One of the pieces of functionality that's been available in many different
00:03 languages, but was missing from PHP, was the ability to dereference strings and
00:08 array literals. Dereferencing means the ability to get
00:11 the address of an item that's stored elsewhere.
00:13 Dereferencing strings is a great way to obfuscate code.
00:17 Meaning it makes it hard to read. So be careful when choosing whether or
00:20 not to use it. I'm going to use array dereferencing to
00:23 get a random element of a one off array without using a variable.
00:28 I'm going to navigate to classes, Log.php and then open the generate method.
00:35 I use this to generate fake log entries. Currently action is blank.
00:40 There are three possible actions. Actions equals array, filled with draw,
00:46 pass, and fold. I'm going to do this the old fashioned
00:51 way first. I'm going to create a new variable,
00:53 random action, and assign it to a random element from the actions array.
00:57 Random action equals actions array rand actions, including setting the key this
01:07 is three lines of code and generated two unnecessary variables.
01:11 I could save a line and just assign action to a random element but there's
01:14 still leftover. Now with PHP 5.5 I can do this in one line.
01:18 I'm going to delete actions and random action and I'm going to create a one off
01:24 array then dereference it using brackets and a key that I wish to access, which is
01:28 a random number between zero and two. So, actions equals array, draw, pass, fold.
01:34 I'm going to dereference accessing a random index key using rand, zero, two.
01:43 If I wanted to strings can be de-referenced in the same way, but for
01:46 this application there really isn't much need.
01:49 Something like echo hello 1, and this would just return e.
01:54 Remove the echo and save the file. This feature probably isn't going to see
01:59 a lot of use, but it makes php more consistent.
02:02 Regardless, now that I have a way of generating log entries, I going to write
02:06 them to the database very quickly, and that can be kind of a sensitive operation.
02:09
Collapse this transcript
Using "finally" with "try" and "catch"
00:00 One of the cooler features of object-oriented PHP is exceptions.
00:05 An exception is a response to an abnormal event that typically requires the
00:08 changing of the normal program execution flow.
00:10 Up to this point, PHP has allowed code to try or attempt to do something.
00:15 If an exception is thrown or created it can be caught, meaning handled gracefully.
00:21 However, some program flows require some kind of closing operation that needs to
00:26 happen even if there is an exceptional situation.
00:30 Here's an example of pseudo code before PHP 5.5.
00:32 I'm going to lock database tables, attempt to write to the database, and
00:38 then unlock the tables. If there's a problem, report the problem
00:42 and unlock the tables. Notice that I have to manually unlock the
00:46 tables in both steps. In PHP a new block is now available
00:51 called Finally. Finally executes after a try/catch block
00:55 and before normal execution resumes, which allows cleanup operation to run
01:00 even if there's a problem. Here's how the same functionality would
01:03 look in PHP 5.5, with less redundant code.
01:08 going to lock tables. Then try writing to the database.
01:11 If there's a problem, I'll catch it. And finally, no matter what, I'll unlock
01:17 the tables at the end. Let's see this in action.
01:20 In NetBeans I'm navigate to pages > generate.inc.php.
01:27 This is a page that will generate a 100 fictitious log entries of a non existent game.
01:32 It starts off with a database connection which I put into exception mode.
01:37 Then I lock the tables. So far, so good.
01:42 I start a try block, where I begin a transaction, prepare a statement, then
01:48 loop through it 100 times. At the end of the loop, I commit, then
01:53 unlock the tables. That's a lot of work in a single try block.
01:56 After the try, There's a catch where if there's a problem I roll back the
02:01 transaction, report that there was a problem and unlock the tables.
02:06 To see this in action, let's go to the browser.
02:09 Click on Generate. I'll see some Success and Info messages.
02:13 I'm going to look into the database to see the generated entries.
02:18 Local host port 8080 and I'm going to go to PHP.myadmin, then I go to Sandbox and
02:24 the log table. There's 100 total.
02:26 Since these are random your rows may look a little different but you get the point.
02:31 I'm going to switch back to the code and clean it up to make it more elegant.
02:36 I'm going to add a finally block after the catch using the finally keyword.
02:40 Finally. Either I'm going to unlock the tables.
02:46 So, unlock the tables. Database.
02:49 Pdo. Exec.
02:50 Unlock tables. And I'll show the success message there.
02:58 I'm going to remove the unlocking from both the catch and the try, and save.
03:06 I'm going to rerun the code in the browser, by clicking on generate again.
03:13 Now when I got back to the table. And I can see that more entries were generated.
03:18 Going back to the application, click on log.
03:22 This is going to render the log, for game one, with no security.
03:27 Let's add a password to this process to only show the game log to somebody who
03:31 has access.
03:31
Collapse this transcript
Security with the password hashing API
00:00 Password hashing is a mechanism that converts a password from a user, into a
00:05 one-way token that can be stored. It's very difficult to reverse engineer
00:09 the token back to the original password. Which adds a strong layer of defense in
00:13 case of a database compromise. Up to this point, password hashing
00:17 libraries such as the portable PHP password hashing framework or PHPass from
00:22 openwall.com were used. Now, there's a standardized and easy to
00:27 use mechanism built into PHP core. There are three primary functions that
00:31 you should be aware of. The first is password_hash which returns
00:36 a hashed password or a FALSE if these are in failure.
00:39 As a couple arguments, the first is $password which is the password to be hashed.
00:43 The second is algo which is always password default for the time being,
00:48 which is the same as PASSWORD_BCRYPT, it's a key derivation function based on
00:52 the Blowfish cipher. And finally, options, which is an array
00:57 that has two keys, salt, which uses an additional input for a one-way password
01:02 hashing to increase complexity and mitigate brute-force attacks, and cost,
01:07 which is passed to crypt to control the amount of CPU time used in creating the hash.
01:12 Higher number is more secure and lower is nicer to the sever.
01:15 When in doubt, find a balance. Cost has a nice default, you can just
01:19 leave it alone, and salt, if you don't include a salt it'll generate one for you.
01:25 If you want to check the output, do store the salt somewhere.
01:29 The next function is password_verify, which takes both a string containing the
01:33 password and a string containing the hash, and gives back a Boolean response.
01:37 Basically, it just verifies that a hash is of a given password.
01:42 The final function that I'd like to discuss is password_get_info, which takes
01:46 a string containing the hash. It'll return an associative array with
01:50 three keys, algo which is the algorithm constant used, algoName which is the
01:57 human-readable name of the algorithm, and options which are the options provided to
02:01 password hash. Pretty straightforward on the grand
02:04 scheme of password hashing, especially with Blowfish support.
02:07 I'm going to implement a very simple password scheme on the log page.
02:11 Let's open log.inc.php. I'm going to start by connecting to the database.
02:18 $database equals new Database. Then, I'm going to get the password hash
02:25 for the current game. I'm going to do that by writing an
02:30 $sql_query, SELECT password_hash. $sql_query FROM game_security.
02:39 $sql_query WHERE game_id equals question mark.
02:44 going to replace that with a $statement equals database, pdo, prepare, $sql_query.
02:54 Then I'm going to execute that statement. $statement execute with an array
03:00 containing log, game_id. If the statement was successful, if statement.
03:08 Get the game security object, $game_security equals statement, fetch, object.
03:15 I'm going to debug the object, so I know what it looks like.
03:19 echo, renderMsg, debug. Albeit an array containing a heading,
03:28 saying game_security as the label. And then, body game_security.
03:37 A little bit of a typo there, I'll fix that up.
03:42 Otherwise, if there was a problem, don't let them in, else, echo renderMsg.
03:49 This will be an error. Could not load the game security record, return.
03:58 Now that I have the password hash, I'm going to get user input.
04:01 I don't consider what I'm about to do appropriate for production environment,
04:04 but it will get the point across. $password equals isset, REQUEST password.
04:11 If it is set, I'll set it to REQUEST password, otherwise an empty string.
04:19 I'll hash the user supplied password. I'm going to pass two constants that are
04:23 set in config.inc.php. $password_hash equals password_hash, and
04:31 I'll pass it the password itself, and then PASSWORD_BCRYPT.
04:39 Then an array with two keys. One for cost, which I'll set to
04:43 PASSWORD_CPU_COST, which I've set in config.inc.
04:48 That's just 7. And then salt, which I will set to
04:54 PASSWORD salt, which is just the string, ILikeLongWalksOnTheBeach.
05:00 Let's see what's created. I'm going to debug the password hash.
05:03 I'm going to copy it from up here, save myself some typing, and paste it down here.
05:09 Instead of $game_security, it'll be $password_hash.
05:15 And for the body, $password_hash. Then I'll debug password verify function, password_verify.
05:26 The body will be password_Verify, which takes password, and the password_hash.
05:34 Make sure it's lowercase, otherwise that will cause problems.
05:37 And finally, I'm going to debug password_get_info.
05:43 password_get_info, which just takes the password hash.
05:47 Enough playing around. I'm going to do the actual check.
05:53 Check the password. If not password_verify, password, then
06:00 we'll compare it to the game security password hash that's stored in the database.
06:05 I'm going to echo renderMsg error. And say, Wrong password.
06:13 And then, return. Otherwise, echo success, Password accepted.
06:24 Let's see this in action. From the browser, reload the Log page.
06:30 This time, I'm going to get a lot of debug information.
06:33 Password verify is when it's verifying the password that it generated.
06:36 There is the information on the password that was generated using the integer 1
06:42 and the name bcrypt with the option of cost 7.
06:46 It will not disclose the salt that was used.
06:49 However, the password was wrong, mostly because I didn't pass it.
06:52 So, let's pass it within the URL. Password equals secret.
06:59 The same checks. But this time, the password is accepted
07:02 and the log is rendered. I like this particular feature a lot,
07:06 especially, because it makes it trivial to create a secure password hash without
07:10 needing an external library.
07:11
Collapse this transcript
Replacing APC with OPcache
00:00 One of the most signficiant features of PHP 5.5 is the inclusion of an opcode
00:04 cache included with a core distribution. Unlike languages such as C, PHP scripts
00:10 are compiled on the fly, then executed by the PHP engine.
00:14 As such, performance can be slower than pre-compiled languages.
00:18 One of the techniques used to avoid these slowdowns is to use what's known as an
00:22 opcode cache, which stores the output of the PHP byte code compiler in shared
00:25 memory for reuse. A common opcode cache is the free and
00:30 open source Alternative PHP Cache, or APC.
00:35 APC is only available as a standalone installation.
00:38 Another common opcode cache is known as Zend Optimizer+, which has been a
00:41 commercial, closed source option then was released recently as open source.
00:47 Why is that important? The reason Zend Optimizer+ was open
00:50 sourced was to allow it to be included in PHP core in version 5.5.
00:55 Now known as OPcache, PHP no longer has a need to separately install an opcode cache.
01:02 Let's do a side by side Benchmark comparison to see what kind of a
01:04 difference an Opcode cache makes. To do that, I'm going to download and
01:08 perform a minimal configuration on a copy of WordPress, an open source content
01:12 management system written in PHP. To perform the test, I'll use
01:17 ApacheBench, which tests a web server by visiting a page over and over again,
01:21 recording statistics and generating a report.
01:25 ApacheBench comes bundled with Apache web server, so no installation is required.
01:30 I'm going to switch to the terminal on my web server, then I'm going to change
01:34 directory to the web root. I'm going to download wordpress using
01:40 wget and then the address http://wordpress.org/wordpress-3.5.1.zip.
01:48 I'm going to extract the file and then switch to the browser to complete installation.
01:55 I'm going to navigate to sandbox.dev.8080/wordpress/wp-admin/install.php.
02:04 I'm going to click Create a Configuration file.
02:09 Let's go. The database name, we'll just call it sandbox.
02:13 Username, sandbox. Password, sandbox.
02:16 Database Host of localhost is fine, and table prefix of wp_ is fine.
02:22 Click Submit, and run the install. For the site title, sandbox.
02:28 For the username, admin is fine. Password, admin admin.
02:34 Your email address, which'll be username@example.com, and I'll allow
02:39 search engines to index the site. Click Install WordPress.
02:45 Success. Just click Log In.
02:48 We'll go to the front page. Just another WordPress site.
02:52 This is a stock WordPress site with no content.
02:55 This is complex enough for a comparison test.
02:57 going to go back to the terminal now. Before I start the benchmark, I'll need
03:01 to add the hostname to the server so I can test it from the server itself.
03:05 I'll type sudo nano dash w etc hosts. It'll ask me for my password.
03:13 I'll add the following line. 127.0.0.1 sandbox.dev, save and exit.
03:24 I'm going to clear the screen. I'm going to use ApacheBench to execute
03:28 100 get requests with five concurrency to the WordPress site.
03:32 To do that, I'll type AB space dash N 100 for 100 requests, dash c for concurrency
03:39 five, and then the address http://sandbox.dev/wordpress with a
03:44 following slash. Looking at these results, it took 25.255 seconds.
03:55 Remember, this is without any kind of op cache.
03:58 Now, let's enable it. I'm going to clear the screen.
04:02 Sudo, nano space dash w opt phpbrew. Php, php55 RC1, et cetera.
04:12 Php.ini. Do a search for op cache, and then I'll
04:16 add the following line. Zend_extension equals opcache.so.
04:24 I'll change opcache enable to one, make sure that it's uncommented.
04:29 In OPCache, enable CLI to one. Save, and exit.
04:34 Then, reload Apache's configuration. Sudo service apache2 reload.
04:41 I'm going to use PHP 5.5 for this session.
04:46 Phpbrew use, php dash, 5.5.0 RC1. Let's verify the php version.
04:56 Php dash v. Good, we're using five five.
04:59 And verify that php now has opcache. Php, dash i, grep, opcache.
05:06 Fantastic. Op cache is now enabled.
05:09 We'll rerun the test. Ab space dash n space 100 space dash c,
05:15 5, then http://sandbox.dev/wordpress with a trailing slash.
05:23 This time, the tests only took 3.731 seconds.
05:30 In this chapter, I've created simple iterators using generators.
05:34 Then I dereferenced strings and arrays. I showed how exception handling can be
05:38 streamlined with try, catch and finally. I added blowfish cryptography to password
05:43 hashing using the password hashing API. Finally, I benchmarked the difference in
05:48 OPcache, the new built-in caching mechanism.
05:52 In the next chapter, I'll discuss updated PHP 5.5 functionality.
05:57
Collapse this transcript
2. Updated PHP 5.5 Functionality
Combining foreach() with list()
00:00 As a developer, one of the common tasks that I see on a regular basis is looping
00:04 over a result set. Depending on the circumstances, I may
00:08 need to assign a group of variables to property values or values in an array.
00:12 Up to this point it's been a manual process, but in PHP 5.5, it's now
00:17 possible to combine for each with List. This allows me to iterate over the array
00:22 and unpack nested arrays into looped variables.
00:25 Using the language construct list as a variable.
00:29 There is a limitation, I can't use list as a key element, which makes sense.
00:33 How am I going to get multiple keys? This sounds neat, in theory, so let's see
00:37 it in action. If we look at the log, we can see it's
00:41 pretty straight forward. And it's rendering some kind of log entry
00:44 that's stored in the database. Let's see what that code looks like.
00:48 I'm going to go back to the IDE. Then navigate to Classes>Log.php.
00:51 Take a look at the method toHtml. There's a 4H Loop that goes through each
01:00 row and sends variables to a method that parses them cleanly.
01:04 Row zero, row one, row two, row three. Now, this is perfectly functional code,
01:09 but talk about ovsication. I could tell the database query to return
01:13 an associative array, which would make it easier to read, but it's still longer.
01:17 Let's try something more elegant using the combination of 4H end list.
01:22 I'll start with only one variable. For each this rows as list player name.
01:28 Then, as the return value, let's return ret val li and then the player name.
01:37 And close the li. Save, then go back to the browser and
01:43 refresh the page. Now, I'm only seeing the player
01:47 identifiers but no errors. Good so far.
01:50 Let's populate the rest of it. Going back to the IDE, assign logical
01:56 variable names to the list, so player name followed by the action, the card,
02:02 underscore text, and the target player name.
02:06 Then, I'll modify the original snippet and pass two string, the player name, the
02:15 action, card text, and target player name, save, and go back to the browser
02:24 and refresh. This time, the entire human readable log
02:28 entry is shown. Something to keep in mind: this technique
02:31 will cause a problem if you have too many variables and not enough data.
02:35 Back to Log, I'm going to intentionally add one additional variable called Too Many.
02:41 Save, then Refresh. As there's not enough elements, a notice
02:46 will be thrown for the undefined offset. I'm going to fix the log now and remove
02:50 that, and Save. To review, PHP 5.5 now allows me to
02:57 combine 4H with List to populate variables from an array or an object that
03:01 can be iterated like an array.
03:02
Collapse this transcript
Checking anything with empty()
00:00 This is kind of a small one, but it's bugged me for a while.
00:02 Checking the return value of a function to see if it's empty.
00:06 If I have no need to know exactly what's returned, then why should I bother with a variable?
00:11 Up to this point, php developers had to explicitly assign a variable to a
00:15 returned value from a function or method. If they didn't, the dreaded can't use
00:20 function return value in right context message would appear.
00:24 To demonstrate this I'm going to pick up cards and discard them until I run out of
00:27 cards in a deck then recycle and shuffle the discards in the deck and continue.
00:32 Let's take a look at Pages > game.inc. A new game is initialized, then for each
00:40 player discard then pick up 30 cards. This is going to run out of cards in a 52
00:46 card deck so, the discard will end up getting recycled.
00:50 Now let's open classes > Game.php and go to method draw cards.
00:57 Looking at line 86 cards this deck get cards.
01:01 If cards is empty then recycle. Now there's a more elegant way of doing this.
01:07 I can just call empty on the function. Let's take out cards, and then, if empty,
01:13 this deck, get cards, then recycle. Let's take a look at the recycle method
01:20 as well. This is doing something very similar,
01:23 deck cards equals this, deck get cards. So we can just cut out the middleman.
01:30 And, if this deck cards is empty, then do the recycle.
01:34 Save, then let's see this in action. Click on Game.
01:39 No errors, so we have the same functionality with less lines of code.
01:42
Collapse this transcript
Normalizing Boolean and unpack() behavior
00:00 PHP 5.5 has included a few normalizations to its behavior.
00:04 The first one I'm going to discuss heavily is relatively trivial and
00:08 technically a new function. Yet at the same time it's an update.
00:12 Joining string val, intval and floatval there's a new player casting about.
00:17 Boolval takes a scalar value and returns a Boolean value.
00:22 This is functionally equivalent as casting as a Boolean.
00:25 But the nice thing is that it can be used as a callback function.
00:29 The other change is that pack() and unpack() are now more compatible with Perl.
00:33 Adding the format Z for stripping trailing NULL padded strings.
00:38 This is functionally equivalent to a. Additionally, for unpack() a no longer
00:43 strips trailing null bytes, which is the same as Perl.
00:46 And capital A, strips all trailing ASCll whitespace.
00:51 If you're writing code with these pack and unpack formats, consider using
00:55 version compare to make sure that you're using code that is appropriate for the
00:58 version of PHP that you're in.
01:00
Collapse this transcript
Removed, incompatible, and deprecated functionality
00:00 Sometimes functionality needs to be gracely retired.
00:04 These changes will have very little impact on most people.
00:06 But it's still important to a small subset of users.
00:09 Windows XP and Windows 2003 support is now officially removed from PHP.
00:14 Additionally PHP no longer supports functions that return PHP logo identifiers.
00:21 Do a quick rep of your code base for the following functions, php logo guid, php
00:27 easter egg logo guid, php real logo guid, and zend logo guid.
00:35 If you have a non English non ASCII code base then you should be aware that case
00:39 and sensitivity is no longer locale specific.
00:43 Matching for function, class and constant names now follows ASCII rules which
00:46 improves support for languages such as Turkish.
00:50 If you have non ASCII characters in multi byte character sets in your code base,
00:54 test before deploying. Now for some deprecations.
00:58 Meaning, that these will be removed in future releases.
01:01 The first is the original MySQL extension, ext mysql.
01:06 Instead use the MySQLi improved extension or PDO MySQL extension, preg replaced/e
01:11 modifier has been deprecated as well. You should be using preg replace callback
01:17 function instead. The method international date formatter
01:22 set time zone ID and function date format set time zone ID are now depricated.
01:27 Use the method set time zone or the function date format set time zone instead.
01:32 Mcrypt has a number of functions that have been deprecated as well including
01:39 mcrypt cbc, mcrypt cfb, mcrypt ecb and mcrypt ofb.
01:46 If you're using those, you should be using mcrypt generic and mdecrypt generic instead.
01:50 That pretty much wraps up the major functional changes in PHP 5.5.
01:54 In this chapter, I've combined for each with list I've checked function return
01:59 values with empty, then discussed how boolean and unpacked behavior has been normalized.
02:06 And finally, reviewed removed, incompatible, and deprecated functionality.
02:11
Collapse this transcript
Conclusion
Farewell
00:00 Performing any version upgrade to a programming language is always a heart
00:04 stopping process. Are the changes good enough to justify
00:07 the time it takes to check for backwards incompatible changes?
00:10 In my opinion, if you're upgrading from PHP 5.3 or 5.4, absolutely.
00:16 You can grab your code bits from effective functions fairly easily, then
00:19 deploy to your developments environment and start exercising the system.
00:23 Remember, incremental upgrades are always easier than monolithic changes, such as
00:27 going from PHP 4 to 5. So, the longer you wait, the harder it's
00:31 going to be. I appreciate your time and your interest
00:34 in PHP. Thanks for watching.
00:36
Collapse this transcript


Suggested courses to watch next:


PHP with MySQL Beyond the Basics (10h 27m)
Kevin Skoglund


Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 104,069 instructional videos.

get started learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 2,024 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.

preview image of new course page

Try our new course pages

Explore our redesigned course pages, and tell us about your experience.

If you want to switch back to the old view, change your site preferences from the my account menu.

Try the new pages No, thanks

site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked