PHP 7 Vulnerabilities You Can’t Ignore

Since its initial release in December 2015, PHP 7 has earned praise by early adopters for its new language features and impressive performance improvements. But developers beware: Glaring security holes lurk beneath the glamour of a new release. In late December 2016, security researchers discovered multiple zero-day exploits in PHP 7, including remote code execution and denial of service vulnerabilities. Attackers can use these exploits to take your site offline or worse—hijack your site for all manner of dastardly deeds.

While the latest PHP 7 releases include patches for these vulnerabilities, the Common Vulnerabilities and Exposures (CVE) List shows that security researchers regularly discover PHP security flaws. In this post you will learn how security breaches can impact your business and what you can do to protect your PHP applications from hackers.

 

Now that we understand the consequences of a security breach, let’s take a closer look at the zero-day exploits discovered in PHP late last year.

Use unserialize()with extreme caution!

The common denominator among all three exploits is PHP’s unserialize() function. PHP 7 introduced a new filtered unserialize feature that aims to mitigate the impact of code injection vulnerabilities by requiring developers to whitelist classes that are safe to unserialize. But even with this improvement, passing untrusted input to unserialize() is not safe, as clearly indicated by the function’s documentation. 

What is untrusted input?

Any input that comes from a source not directly under your control should be considered dangerous. Examples of input sources include query string parameters, HTML forms, file uploads, third-party APIs, and more.

Is my site vulnerable?

The only way to know if your site is vulnerable is to inspect your entire codebase and all of its dependencies. Typically the vulnerability report, such as this one for CVE-2016-7479, includes enough information for you to identify vulnerable code. However, each vulnerability is unique, making it unfeasible to manually inspect your codebase for every possible vulnerability—not to mention you have to repeat these inspections every time you change your code or new vulnerabilities are discovered.

How do I fix it?

The immediate fix is to update to the latest patched version of PHP 7. If that’s not possible because you are using shared hosting or because upgrading could break your application, you need to implement a workaround. Even if you can upgrade PHP, you should still consider a workaround because unserialize() is historically risky and likely still contains undiscovered vulnerabilities. In this case, the safest approach is to use an alternative serialization format, such as JSON, that can deserialize data without loading or executing additional PHP code. 

Building a foundation for PHP security

At this point your head may be spinning—and we’ve only covered a single PHP 7 vulnerability. Fortunately, there are many industry standard tools and practices available to help you make your site more secure without losing sleep or breaking the bank. Even adhering to only two or three of these recommendations will put you in a more secure posture than many organizations.

Patching schedule

This one isn’t PHP specific, but if you don’t keep your operating system and PHP version up to date with the latest security patches, nothing else you do matters. Most Linux distributions include PHP in their package repository, and they update it regularly with the latest security patches. Enabling automatic security updates for your OS is the absolute minimum you can do. If you install PHP from source or some other method, you should use configuration management software such as Ansible, Chef, or Puppet to automate the installation and upgrade process.

Dependency checks

Most production PHP applications depend on dozens of third-party libraries directly, and even more libraries indirectly. Each one of these components may have security flaws and require regular updates. For this reason, many development teams use Composer to simplify management of their app’s dependencies. But how do you know when you need to update?

 The open source OWASP dependency-check tool can identify vulnerable Composer packages in your application. As a bonus, if you use NPM to manage JavaScript packages, dependency-check works on those too.

Secure coding practices

Unless your application lives in a vacuum, you will make code changes on a regular basis. Any developer involved with building or reviewing PHP applications should have a basic knowledge of common web application vulnerabilities and secure coding practices.

 Understanding the OWASP Top 10 is a good foundation for general web application security knowledge. Attack vectors such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF) are common to web applications written in any programming language.

 The next level of security knowledge is to know the specific security considerations and concerns for the PHP language. There are good online guides available to get you started, and the PHP manual itself has an entire section devoted to security.

Static analysis

Static analysis tools read and analyze your application source code, looking for common security vulnerabilities and insecure code structures. For example, the Exakat PHP security scanner can identify unsafe use of the unserialize() function that we examined earlier. Drawbacks of static analysis tools include incomplete rulesets and false positives. There are many open source and commercial PHP static analysis tools available, so do your homework and find ones that work well for you. While they often provide quick and useful feedback on the security of your code, static analysis should never be used as your only security control.

Dynamic analysis

While static analysis tools examine your application’s source code, dynamic analysis tools, such as Arachni or the OWASP Zed Attack Proxy, observe the behavior of running applications. These tools crawl your site, click on links, fill out forms, and do all kinds of unexpected things to your site in order to discover classes of vulnerabilities that can’t be detected using static analysis. If at all possible, you should run these tools against a test instance of your application and not a production site, because they can potentially modify data or break your site.

Make security part of your CI/CD pipeline

Good PHP application security takes time, requires expertise, and demands a broad toolset. If you don’t automate the basics and make security visible, your team will inevitably drift back into poor security habits. One of the best ways to establish a sustainable application security baseline is to integrate security controls into your continuous integration pipeline. Many of the security tools mentioned previously have scriptable command-line interfaces, and some even have first-class CI support, such as the OWASP dependency-check and ZAP plugins for Jenkins.

 When developers notice security issues in their build status reports, they will naturally start fixing them as part of their daily work. Advanced teams will even fail the build when a security check fails, preventing deployment until they can patch the issue. Instead of taking weeks, months, or even years to detect and remediate most security vulnerabilities, you can have a Zero mean time to remediation (MTTR). You can find and fix security problems before unleashing your code on the internet.

Web application firewalls

What about application security problems that arise in production? Despite your best efforts to build security into your product, there will always be opportunities for attackers to exploit your application in the wild. While advanced security monitoring and incident response are beyond the scope of this article, one simple solution that offers substantial security benefits is to use a web application firewall in front of your site.

 Web application firewalls (WAF) stop malicious requests before they can reach your servers. Not only can a WAF prevent common types of attacks, it can also block traffic from sources known for malicious activity. Most commercial web application firewalls act as a reverse proxy and require little to no application or hosting changes to start using. ModSecurity is an open source WAF module you can install on your Apache, Nginx, or Microsoft IIS web server. With the modern increase in threat activity and rise of massive botnets, leveraging a WAF is quickly becoming a requirement for site owners.

Conclusion

Security vulnerabilities are a fact of life. While a security breach can be damaging to your business, there are plenty of ways you can protect your PHP sites and mitigate your risk that don’t require you to be a security genius. Don’t let the recent discovery of PHP 7 security vulnerabilities discourage you from using the latest and greatest version. With the right training, awareness, tools, and practices, you can safely run PHP 7 applications in production today and in the future.

 

The Top 5 Worldwide PHP Conferences

Despite the rapid growth of new programming languages and platforms, PHP continues to be a stable workforce that powers much of the web. More than 82 percent of the internet is powered with server-side programming apps using PHP — more than ASP.NET, Java, and ColdFusion. For a while, it looked like other stacks might surpass PHP. However, with the release of the first major update in more than ten years, PHP 7 has silenced many critics.

PHP conferences continue to offer attendees the opportunity to learn new skills, keep up on PHP developments, discover recent trends, view the latest technologies offered by exhibitors, and meet new friends and contacts in the industry. Here are five of the top PHP conferences around the world you should consider attending to broaden your horizons, update your skill set, and build relationships with key developers and decision makers.

SunshinePHP

The SunshinePHP conference is held in the first part of the year in Miami, Florida, usually in February. It is produced by the South Florida PHP Community and features speakers, talk topics, panels, breakout sessions on the latest news, best practices, and technologies related to PHP. The conference lasts three days, with the first day filled with in-depth workshops and tutorials. The following two days feature high-level industry keynote speakers as well as more than 40 talks about PHP covering four different tracks.

SunshinePHP is directed to veteran programmers and newbies alike. It is organized and hosted by working developers at the South Florida PHP Community, so it naturally focuses on current industry topics and real-world challenges. The 2017 SunshinePHP conference will be its fifth consecutive year and it set for February 4 – 7, 2017 in Miami, Florida. It sells out every year, so be sure to plan ahead.

In 2016, around twenty companies sent at least five developers, and several others sent around ten developers. Conference sponsor participation was also strong, with a majority of participants taking space in the exhibit area.

At that conference, several topics were discussed that aren’t normally covered at many PHP conferences. For example, speeches covered diverse areas such as teamwork and collaboration, how rest affects the way we think, brain functionality, how humans learn, and how to help customers and developers meet mutual goals.

The 2016 conference speaker lineup consisted of 36 percent female speakers and 20 percent female convention attendees. These were promising numbers, as all areas of tech seek to engage more women in the industry. Evening hours were spent with panel discussions and games, as well as an outdoor buffet and a fully stocked bar.

Despite the growth of newer technologies such as Node.js and Go, PHP remains dominant. Review these five top PHP conferences, as well as regional conferences in your area, and make plans to attend one in the future. You’ll improve your techniques, insight, and programming skills while developing contacts from around the world. You’ll find that every conference has friendly and welcoming organizers, and you’ll enjoy the entire experience.

Confoo

Confoo is the biggest web technology convention in North America. The 2016 conference was held from December 5 – 7 in Vancouver, B.C., Canada, and the 2017 Confoo conference is set for March 8 – 10, 2017 in Montreal, Canada. A couple of the 2016 speakers included Adam Culp, Abraham Williams, Anna Filina, Billy Gregory, and Brittany Martin. Sessions were extremely diverse. Past talks have included “An introduction to deep learning” and “Extremely defensive PHP programming.”

Attendees from past Confoo conferences comment that they like the wide variety of technologies, knowledgeable attendees who are eager to share information, the opportunity to learn new concepts from developers around the world, understanding how your current skill set matches up with market demand, cutting-edge sessions, the multi-language approach, and the open and friendly atmosphere.

php[tek]

php[tek] is one of the older conferences, organized since 2006 by the group behind php[architect] magazine. It has long been dubbed informally by attendees as the PHP community’s “annual homecoming,” so conference organizers adopted the phrase as their slogan. The conference takes place around May every year, and tries to focus less on business interests and more on the interests of the attendees. The 2017 php[tek] conference is the twelfth edition, and is slated next for a May 24 – 25, 2017 in Atlanta, Georgia.

The 2016 event displayed innovation in the form of live streams of keynote speakers and several key events. Videos of the captured streams are featured on the php[architect] YouTube channel. The first day focused on PHP and Laravel basics and web security. The second day had a full slate of PHP tutorials.

Like SunshinePHP, php[tek] places a strong emphasis on community. The organizing team consists entirely of members of the PHP community. The emphasis is on core PHP elements, as well as related topics such as JavaScript, MongoDB, and others. There are sessions for both new and experienced developers.

php[tek] develops fun ways to increase participation from attendees, using games and puzzles throughout the conference, with cool prizes awarded. There is plenty of opportunity for socializing — past events have included community nights, a casino night, newcomer sessions, and designated open spaces.

There is also an emphasis on looking down the road to upcoming developments with PHP and working to test new features as soon as possible. For example, past conferences stressed the importance of adapting PHP 7 as soon as possible, and getting involved in reporting issues to help eradicate problems as the new version was rolled out.

Speaker preview videos are posted on the conference website as they become available. You can also stay up-to-date with conference developments and news on their Twitter feed at @phparch.

Dutch PHP

Self-identifying as “Europe’s Most Exciting Web Conference,” Dutch PHP ran June 23 – 25, 2016 in Amsterdam, Netherlands and it’s set to appear in the same city from June 29 – July 1, 2017. Organized by Ibuildings, the convention is completely in English. The focus is on networking, best practices, know-how, technology, and tips and tricks. Ibuildings is a company that was founded in 1999. They began with PHP and then grew to incorporate other runtimes. The 2016 convention was the tenth edition of the Dutch PHP Conference.

Dutch PHP is targeted toward mobile web and PHP developers at every experience level. They encourage decision-makers outside of the developer community to attend, such as management and vendors. Experienced developers will learn how to refine their current programming skills, as well as take away new knowledge about the latest technologies. Beginning programmers will learn techniques to expand their knowledge and grow their skill set faster.

Past speakers have included John Ledrew, Dennis Degreef, Niels Nijens, Luis Cobucci, and Sara Golemon. Session topics have included such diverse areas as modern databases, lightning fast testing, containerizing in a production environment, migrating PHP extensions, graph databases, message-oriented architectures, PHP generators, secrets of cryptography, and solving cross-cutting concerns and PHP.

Past attendees have commented that the venue is large and the event is well organized by the staff. There are many standup tables to meet with other attendees while enjoying a refreshment, but there are also a number of sitting desks available if you want to do some work in between sessions. They also enjoyed the code night after the main sessions, where they can improve several open-source projects. They also commented that the talks were well presented with a wide variety of topics beyond PHP, including CSS, testing, JavaScript, DevOps, and more.

php[world]

Like php[tek], php[world] is hosted by the folks at php[architect] magazine. This conference is specifically organized to bring together the wide variety of PHP frameworks such as Joomla!, Zend Framework, Laravel, Drupal, Magento, CakePHP, WordPress, and Symfony.

The 2016 conference was November 14 – 18 at the Sheraton Premiere at Tyson’s Corner near Washington, D.C., close to the Dulles airport. Past speakers have included Eryn O’Neil, Michelangelo van Dam, Edward Finkler, and Helen Hou-Sandi. The 2017 conference date is not yet announced.

This conference is designed to bring together the various PHP platforms into one event that discusses their shared concerns and challenges. With more than 80 percent of the internet running on PHP, the number of PHP frameworks has grown and fragmented. php[world] was designed from the ground up for developers from these different platforms to share ideas and best practices. Conference topics have included web security, object-oriented PHP, PHP essentials, containerizing PHP applications, building APIs, REST APIs, PHP, and IoT, using open source for small business operations and much more.

As Drupal, WordPress, and the other platforms listed have grown, users began to think of themselves as developers for each specific framework, instead of as a PHP developer first. The conference is geared toward learning from each other across framework walls, even as they begin to merge into each other. For example, Magento has become increasingly based on Zend Framework, and Drupal has incorporated core libraries from Symfony. Sessions are spread over eight tracks, with talks on each platform as well as cross-over sessions.

 

Battle of the PaaS: PHP Apps in the Cloud

Platform as a Service (PaaS) providers have grown rapidly over the last few years. Now you can choose from a number of robust services that can help you rapidly develop, deploy and manage your PHP application. To help you make sense of this crowded market, this article will examine the features, benefits and drawbacks of five of the most popular platforms right now: Heroku, Google App Engine, Microsoft Windows Azure, Amazon Web Services (AWS) and Engine Yard — and help you determine which option is best for you.

Heroku

Heroku is a web hosting company that began with Ruby on Rails apps and now handles PHP, Java, Clojure, Go, Scala and Node.js. The service started operations in 2007, making it one of the pioneering cloud platforms. Acquired by Salesforce in 2010, it is free for small applications. If you get more traffic, you can expand your account and scale your costs economically.

Although there are cheaper providers, Heroku is well-known and popular. But Heroku can become expensive quickly when you order several dynos. Dynos are Linux containers that handle a single command — any command that is part of the default environment or in the slug, which is a pre-prepared and compressed copy of the app and related dependencies. One way to save money is to invest in additional services rather than defaulting to adding more dynos.

Heroku is ideal for building applications quickly. Setup is painless — much of the operation is hidden from you by design. The whole idea is to make the process simple. Heroku customers include Code for America, Rapportive, TED, Facebook, Lyft, Urban Dictionary, GitHub and Mailchimp.

Google App Engine

Google App Engine is ideal for creating scalable web apps and backends for mobile apps. You get a number of services and APIs including Memcache, NoSQL datastores and user authentication. Your apps will be scaled automatically depending on the amount of traffic they get, so you only lay out cash for what you use.

You do not have to worry about provisioning or maintaining servers. Services such as application logging, health checks and load-balancing allow you to deploy your app quickly. App Engine is compatible with common development tools including Git, Jenkins and Maven.

While Google App Engine is easy to use, it might also be considered a weakness. Many things are handled automatically, but if you want to customize it to your liking, you may be frustrated. Customers using Google App Engine include Gigya, NewsLimited, Mimiboard, Khan Academy, WebFilings, Best Buy, MetOffice, Getaround and CloudLock.

Microsoft Windows Azure

Like Amazon AWS, Windows Azure is really a combination of IaaS and PaaS. It supports PHP, .NET, Node.js, Ruby, Python and Java. You can utilize Visual Studio for building and deploying PHP applications. Options include an SQL Database, Blobs and Tables for persistent storage. You can administer your app with the command line or Windows Azure dashboard.

Because Azure is effectively both a PaaS and IaaS at the same time, you have a broad selection of components you can assemble for a custom solution, giving you lots of control over the process. On the other hand, Azure has a stripped-down administrative portal that may seem too sparse to some developers.

There are no upfront costs to use Windows Azure. You pay for only what you use, and there are no termination fees. Azure has been used by companies such as BMW, easyJet, HarperCollins, TalkTalk, Telenor, Toyota, Avanade, NBC Sports and Aviva.

Amazon Web Services

Although Amazon Web Services is better known as an Infrastructure as a Service (IaaS), it offers many of the features available on a PaaS. You can utilize the services available in Amazon AWS without resorting to building and maintaining application servers on your own. Because the AWS server is a raw OS, you can implement any language you choose including PHP, Ruby, Python and other languages. You can tap the power of Amazon Elastic Beanstalk for autoscaling, application health monitoring and automatic load-balancing.

You can use the AWS Software Development Kit for PHP library, documentation and code samples. At the AWS PHP Developer Center, you’ll also discover:

  • How to deploy PHP apps on AWS Elastic Beanstalk and AWS OpsWorks.
  • Access to white papers created by the AWS team on an array of technical topics including economics, security and architecture.
  • How to connect with other developers via GitHub, the PHP Developers Blog, Community Forum and Twitter.

One great advantage is you can get started on AWS for free to give you hands-on experience. The Free Tier offers 12 months of service at no charge. You can employ any of the services and products within specific usage limits. Feature products include Amazon EC2 compute capacity, Amazon S3 storage infrastructure, Amazon RDS relational database service, AWS IoT for connecting devices to the cloud and Amazon EC2 Container Registry used to store and retrieve Docker images. One of the drawbacks of Amazon AWS is that you may need to handle more management than other PaaS providers. The AWS client list has included GE, Pinterest, Netflix, Pfizer and Nasdaq.

Engine Yard

Engine Yard is for developers who are creating Node.js, Ruby on Rails and PHP applications and want the power of the cloud without the hassle of operations management. Many of the services are provided on top of Amazon AWS. Engine Yard itself is a run on Amazon. That’s why its strengths are management and orchestration more so than providing a deep bench of components. With Engine Yard, you can manage snapshots, administer databases, manage clusters, perform backups and do load-balancing. Engine Yard’s advantages include dedicated instances, lots of control over virtual machine instances and integration with private and public Git repositories. It is considered by some to be a “heavier” PaaS than Heroku, meaning they believe it should be used for more heavy-duty, serious applications.

One reviewer said that Heroku is nice for setting up apps quickly, but serious apps need Engine Yard. Not everyone agrees, however. Another reviewer reported felt Heroku was far better than Engine Yard, saying that you can install gem and have your app deployed in just a few minutes. Pricing for Engine Yard is a pay-as-you-go model. There are premium options along with standard setups. Pricing ranges from $25/month for a solo instance to $150/month for a standard instance and $300/month for a premium instance. Engine Yard accounts include Appboy, Vitrue, TST Media, RepairPal, MTV, Badgeville and Estée Lauder.

Review and Recommendations

So what have we learned?

  • Heroku is easy to manage, well-known, simple to use and is great for building apps rapidly. It can get pricey, so you need to manage dynos carefully.
  • Google App Engine is well-suited for managing back-end operations of mobile apps and creating web apps that can scale. Although simple to use, it is not easy to customize.
  • Azure has gained market share quickly by providing lots of components and user control. Its hybrid IaaS/PaaS personality allows both Windows and Linux users to find a solution on the platform.
  • Amazon Web Services is a proven system that has recently cut prices due to competition from Azure and others. There are many support and educational resources to tap into including the Developer Center, a blog for programmers and an online forum for community members.
  • Engine Yard has excellent management and orchestration tools, as well as great support and robust scaling options. It can be harder to master than other platforms, but is excellent for those new to PaaS platforms that need more support to get up and running.

Adoption of cloud technology will continue to grow as organizations shift apps from internal data centers to the cloud to cut expenses and become more nimble. These five PaaS platforms will help you get your PHP app up and running quickly to take advantage of the on-going move to the cloud.

Choosing the Right PaaS

Choosing the right PaaS comes down to evaluating your cloud goals and the needs of your developers. Start with your target language, in this case, PHP. Every layer of the LAMP stack has more depth than ever before, and most PaaS providers are language agnostic, even if they initially supported only a single language.

Also, consider if you will benefit from a PaaS that functions as a quasi-IaaS/PaaS. Hybrid models provide several advantages. For example, you may have a database that is too large to handle in the cloud and is better suited to be located on-site. A hybrid approach lets you access local data from the cloud quickly. One disadvantage of this setup is having to worry about configuring an abstraction layer, which means your team needs the training and know-how to maintain it.

Other considerations are: How will you achieve scalability? Will you be able to move apps quickly away from your PaaS if needed? PaaS does not always mean development in the cloud. The advantage is simple deployment of applications which saves you time, money and hassle with your next PHP web application.

 

Top Performance Metrics for Java, .NET, PHP, Node.js, and Python

No application is the same. Some legacy apps were built in a monolithic environment built on a homogeneous language, say Java or .NET. As environments become more distributed, and technology has innovated to a near-breaking speed, application architectures tend to be built using a multitude of languages often leveraging the more dynamic languages for specific use cases.

Luckily, these distributed and extremely complex environments are where AppDynamics thrives with monitoring. AppDynamics supports Java, .NET, PHP, Node.js, Python, C/C++, and any combination of them — fitting nearly any environment.

After speaking with several customers and analyzing their performance, we’ve compiled a list of the most common performance problems for each language and the performance metrics to help measure your application health.

Below, we’ve compiled a brief summary of our findings and link to the full analysis in the respective complimentary eBooks.

Top Java Performance Metrics

Java remains one of the most widely used technology languages in enterprise applications. However, though it’s so widespread, it’s a clunky legacy language that can often have performance issues.

Along with monitoring external dependencies, garbage collection, and having a solid caching strategy, it’s important to measure business transactions. We define a business transaction as any end-user interaction with the application. These could include adding something to a cart, logging in, or any other interaction. It’s vital to measure the response times of these transactions to understand fully your user experience. If a response time takes longer than the norm, it’s important to get this resolved as quickly as possible to maintain optimal user experience.

Read the full eBook, Top 5 Java Performance Metrics, Tips & Tricks here.

Top .NET Performance Metrics

There are times in your application code when you want to ensure that only a single thread can execute a subset of code at a time. Examples include accessing shared software resources, such as a single threaded rule execution component, and shared infrastructure resources, such as a file handle or a network connection. The .NET framework provides different types of synchronization strategies, including locks/monitors, inter-process mutexes, and specialized locks like the Reader/Writer lock.

Regardless of why you have to synchronize your code or of the mechanism you choose to synchronize your code, you are left with a problem: there is a portion of your code that can only be executed by one thread at a time.

In addition to synchronization and locking, make sure to measure excessive or unnecessary logging, code dependencies, and underlying database and infrastructure issues.

Read the full eBook, Top 5 .NET Performance Metrics, Tips & Tricks here.

Top PHP Performance Metrics

Your PHP application may be utilizing a backend database, a caching layer, or possibly even a queue server as it offloads I/O intensive blocking tasks onto worker servers to process in the background. Whatever the backend your PHP application interfaces with, the latency to these backend services can affect the performance of your PHP application performance. The various types of internal exit calls may include:

  • SQL databases
  • NoSQL servers
  • In-memory cache
  • Internal services
  • Queue servers

In some environments, your PHP application may be interfacing with an obscure backend or messaging/queue server. For example, you may have an old message broker serving as an interface between your PHP application and other applications. While this message broker may be outdated, it is nevertheless part of an older architecture and is part of the ecosystem in which your distributed applications communicate with.

Along with monitoring the internal dependencies, make sure you measure your business transaction response time (as described above), external calls, and have an optimal caching strategy with full visibility into your application topography.

Read the full eBook, Top 5 PHP Performance Metrics, Tips & Tricks here.

Top Node.js Performance Metrics

In order to understand what metrics to collect surrounding Node.js event loop behavior, it helps to first understand what the event loop actually is and how it can potentially impact your application performance. For illustrative purposes, you may think of the event loop as an infinite loop executing code in a queue. For each iteration within the infinite loop, the event loop executes a block of synchronous code. Node.js – being single-threaded and non-blocking – will then pick up the next block of code, or tick, waiting in the queue as it continue to execute more code. Although it is a non-blocking model, various events that potentially could be considered blocking include:

  • Accessing a file on disk
  • Querying a database
  • Requesting data from a remote webservice

With Javascript (the language of Node.js), you can perform all your I/O operations with the advantage of callbacks. This provides the advantage of the execution stream moving on to execute other code while your I/O is performing in the background. Node.js will execute the code awaiting in the Event Queue, execute it on a thread from the available thread pool, and then move on to the next code in queue. As soon as your code is completed, it then returns and the callback is instructed to execute additional code as it eventually completes the entire transaction.

In addition to event loops, make sure to monitor external dependencies, memory leaks, business transaction response time, and have a full and complete view of your application topography.

Read the full eBook, Top 5 Node.js Performance Metrics, Tips & Tricks here.

Top Python Performance Metrics

It is always faster to serve an object from memory than it is to make a network call to retrieve the object from a system like a database; caches provide a mechanism for storing object instances locally to avoid this network round trip. But caches can present their own performance challenges if they are not properly configured. Common caching problems include:

  • Loading too much data into the cache
  • Not properly sizing the cache

When measuring the performance of a cache, you need to identify the number of objects loaded into the cache and then track the percentage of those objects that are being used. The key metrics to look at are the cache hit ratio and the number of objects that are being ejected from the cache. The cache hit count, or hit ratio, reports the number of object requests that are served from cache rather than requiring a network trip to retrieve the object. If the cache is huge, the hit ratio is tiny (under 10% or 20%), and you are not seeing many objects ejected from the cache then this is an indicator that you are loading too much data into the cache. In other words, your cache is large enough that it is not thrashing (see below) and contains a lot of data that is not being used.

In addition to measure your caching, also, monitor your external calls, application visibility, and internal dependencies.

In addition to measure your caching, also monitor your external calls, application visibility, and internal dependencies.

Read the full eBook, Top 5 Python Performance Metrics, Tips & Tricks here.

To recap, if you’d like to read our language-specific best practices, please click on one of the links below:

Predicting the Future of PHP Security – Part 3

In some ways security is an infinite game of chess on a board the size of the world. For every move you make, the hackers have a countermove ready. They are highly motivated to take what you have, so the game never ends; it just switches players once in awhile. In this final blog in the series, we are going to review the game board, with a look at the most recent changes to security in PHP 7 and earlier supported versions. Then, we’ll try to look a few moves ahead with predictions for the future of PHP security.

The Problem with Popularity

It is understandable that PHP has attracted a considerable amount of attention from hackers because it is one of the most popular programming languages on Earth, according to the TIOBE index.

In various versions, PHP is currently running underneath the vast majority of sites on the web. Web Technology Surveys reported that PHP is used by about 82 percent of all websites where it is possible to know the server-side language.

PHP 7 Released

The biggest change in the landscape since we left off in Part 2, is that PHP has gone in for a complete makeover. PHP 7 was released in December, the first major update in more than a decade and coming in with an emphasis on faster loads and new functionalities. In case you were wondering what ever happened to PHP 6, it did not happen at all. Unicode failures were too severe, and it had to be scrapped.

This year, some security updates have already been issued, so check on the PHP.net site to make sure you have the latest update. They are also still supporting the 5.5 and 5.6 release with a number of security patches.

The new release is confirmed to be faster and more stable by plenty of benchmarks and testing sites. The official benchmarks validate PHP 7 running twice the speed of PHP 5.6 in common deployments. The update handles double the number of requests per second, so most users with typical applications like WordPress sites will see a noticeably faster load. For those running data centers, they will essentially double their capacity for running more applications or features.

Security Upgrades in PHP 7

There are still some serious issues with security, however. In their State of Software Security Report 2015, Veracode performed cloud-based scans and code analysis of more than 50,000 applications. They reported that approximately 86 percent of PHP applications showed evidence of cross-site scripting (XSS). Also, more than half (56 percent) appeared to have with at least one SQL injection bug. In part one of this series, we discussed how to handle both of those common flaws in PHP. Below are some of the significant security upgrades in PHP 7.

Whitelist Classes

The new filtered unserialize() feature is a more secure approach to unserializing objects in un-trusted data. You will be able to whitelist classes that can be unserialized to head off the possibility of code injections. This lets you pass complex data structures around as strings.

Cryptographically Secure Random Numbers

There are now two ways to generate both integers and strings. If you are coming from another object-oriented language, you may be thrilled to see these two.

string random_bytes ( int $length )

and

int random_int ( int $min , int $max )

These are useful any time that you need unbiased results. Also, if you are still running an earlier version of PHP, you can apply these functions with this userland implementation (for PHP versions 5.2 – 5.6).

Override Configurations

If you ever need to completely override session configuration directives in php.ini, you can now handle it with

bool session_start ([ array $options = [] ] )

The PHP manual explains:

“This creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.

The save handlers you use could be ready-built ones that were provided by default, or you could use PHP extensions like SQLite or Memcached. The other option you have is to use a custom handler that you would define in:

bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid ] )

Of course, the read callback here can retrieve any existing session data that is stored in a special serialized format. It will be unserialized and used to automatically populate the $_SESSION superglobal. That will be after the read callback returns saved session data back to your PHP session handling.

These are so important because custom save handlers give you more flexibility in what you do with the session data. For example, you can lower the risk of unauthorized use of a session by ending the session after a specified idle time.

Additional PHP Security Patches

In January, the PHP 7.0.2 update was released to address 31 reported errors and six of those were to seal off potential security vulnerabilities. At the same time, the older versions got updates too. PHP 5.6.17 addressed problems with 14 identified bugs, and PHP 5.5.31 was designed to close vulnerability loopholes. The developer announced that PHP 5.5 will be in security support mode from now until July 2016.

In terms of security, it is also critical to note that PHP 5.4 is no longer maintained, so if you are running that version, your site or application will be vulnerable to all kinds of attacks and exploits. Here are some of the potential attacks and remote code execution routines that the latest updates we designed to counter.

Buffer Overflows

PHP fixed a heap buffer overflow to prevent a hacker from passing a string longer than 1 billion characters to

escapeshellarg()

The end goal is to overwrite the return pointer of the function. The hacker might then be able to change the flow of the code execution.

Memory Leaks

Another update addressed the memory read error in the GD graphics library. In the past, hackers could use this vulnerability to gain access to substantial and contiguous chunks of your memory. It works by passing a large number that exceeds the color palette array to ImageRotate.

Another potential memory leak that was plugged up was an error in FPM, the FastCGI Process Manager. In the older versions, whenever a long token like an HTTP request with an extra-long query string came at the end of the access.format option of FPM, the code would try to write outside the compiled buffer. PHP listed the severity as low because several other conditions would have to exist in addition before hackers could exploit this vulnerability.

Remote Code Executions

A potentially more serious threat was addressed by closing up the user-after-free vulnerability in WDDX, the Web Distributed Data eXchange interface. Hackers would have been able to remotely execute malicious code if this were still in place. Even when values are freed from memory during packet deserialization, malicious recordsets could gain use of the free memory.

Type Confusion

One update was targeted at eliminating type confusion vulnerabilities in WDDX. These left applications open to remote code execution attacks. Hackers would have been able to deserialize a string type and create their own hash table to insert.

Updates also addressed a second type confusion vulnerability in XMLRPC-EPI, which is the XML-RPC protocol for PHP. This would have left a door open for hackers to do a lookup on arbitrary memory addresses. That could lead to memory leaks or a complete crash of your PHP code.

What’s Coming Next for PHP

Adam Englander at LaunchKey made a significant prediction about where PHP might be headed in the very near future. Englander, speaking to other PHP developers at Reddit, said:

“You will start to see some movement into real hardware level Internet of Things (IoT) development in PHP. With a true asynchronous programming framework to take advantage of asynchronous I/O, you will now be able to write PHP applications to easily receive input from GPIO based hardware on Raspberry Pi, Intel Edison, and other IoT devices running Linux operating systems.”

It makes perfect sense that PHP will be looking for ways to expand its interoperability with other frameworks this year, and IoT is a field where a great of development is happening right now. As you may have noticed at CES this year, a host of consumer and professional markets are filling up with IoT devices and applications.

The problem is that security will need to get much tighter for PHP applications in IoT applications that interface with cars, automated door locks, location services, private identifying information and a host of other things that hackers will be extremely interested in accessing.

Getting the security piece right is incredibly important, and even more so, it is an enormous opportunity for any developers hoping to stay one move ahead of the hackers.

Just in case you missed anything, here’s a TL;DR for the entire blog:

  • PHP is super popular, running under around 82 percent of websites. That is why so many hackers want to break it.
  • PHP 7 just came out, the first major update in more than ten years.
  • You can now whitelist classes by unserializing untrusted data.
  • You can generate cryptographically secure random numbers
  • You can reset and override session configuration.
  • Patches addressed buffer overflows, memory leaks, remote code executions and type confusion vulnerabilities.
  • In the very near future, expect to see PHP working its way into the Internet of Things (IoT). That will issue in a new era of security concerns and advances.

Everything You Need to Know about PHP 7

PHP 7 is the latest version of the popular programming language PHP. Released in December 2015, PHP 7 offers fast performance for websites and online applications. There are some significant differences between PHP 7 and the previous version of the language, PHP 5.6. Let’s take a look at the answers to some of the most common questions about PHP 7.

What About PHP 6?

Don’t worry, you did not miss the last version. In 2005, the PHP community started working on the development of PHP 6, but the project stalled. As the years went by, the reputation of PHP 6 deteriorated to the point that the community no longer wanted to continue using the name. Therefore, the version of the language that eventually replaced PHP 5.6 was given the name PHP 7.

What Drove the Need for PHP 7?

PHP is an extremely popular programming language. Created in 1994 by Rasmus Lerdorf, PHP has grown in popularity to the extent that today, nearly 82 percent of websites use PHP, which means that most of the Web relies on the language to at least some extent. With an increasing number of people coming online, including a rapidly growing number of mobile users who often rely on relatively slow 3G connections, it is necessary for the servers that power the world’s websites to be able to react quickly to user requests. Studies show that 40 percent of people will abandon a web page that takes more than three seconds to load, demonstrating that speed is a crucial factor in website design.

Significant changes to PHP have increased the performance of sites that use the language dramatically. In fact, it is estimated that PHP 7 offers a 100 percent improvement in performance speed over PHP 5.6. This major improvement in speed allows web developers to create sites that provide interesting and engaging interactive features that still respond to user input as quickly as modern web users have come to expect.

Another motivation for the development of PHP 7 is the need to develop scripting languages that run more efficiently. This demand is driven by two factors: the need to reduce costs and the need to reduce power consumption to protect the environment. Compared to PHP 5.6, PHP 7 places substantially reduced demands on servers, which makes it a more cost-effective and environmentally friendly choice, as comparatively less energy is needed to power servers running PHP 7 applications.

Who Spearheaded the Development of PHP 7?

The development of PHP 7 was spearheaded by Dmitry Stogov, Xinchen Hui, and Nikita Popov. These three developers created an experimental branch of PHP that they originally called PHP Next Generation, often abbreviated as PHPNG. The PHP community embraced this new branch of the scripting language, as it offered significant improvements in performance, and continued to develop it into the stable version of the language now known as PHP 7.

PHP 7 has been through several months of beta testing and was finally released in its stable form in December 2015, just one month after the predicted release date.

What Is New in PHP 7?

The headline change associated with PHP 7 is the significant improvement in performance. Roughly twice as fast as PHP 5.6, PHP 7 can compete with modern competitors to pure PHP, such as Facebook’s Hip Hop Virtual Machine (HHVM). In fact, for Drupal users, PHP 7 offers even faster performance than HHVM, with the added benefit of not needing to use a virtual machine to execute the PHP source code. Also, when PHP 7 runs on WordPress 4.1.1, it can execute twice as many requests per second as the same platform running PHP 5.6.

In addition to better performance, the following technical changes appear in PHP 7. Developers should familiarize themselves with these changes if they intend to switch over to using PHP 7 for their web development projects.

Return Types

Return types, a common feature in most other programming languages, have finally been introduced to PHP. This means that programmers can now specify the type of variable that a function should return. In PHP 7, the return type is specified after the closing parenthesis of the argument list:

function foo(): array { 

return []; 

}

This example declares a function “foo” that returns an array. In PHP 5.6, programmers would not specify the return type, which means that it is not clear to anyone reading the code what the function “foo” is supposed to output. Explicitly declaring return types makes code much easier to read, which is useful when debugging your code or working with code that was written by someone else.

Spaceship Operator

One interesting change to the syntax of PHP 7 is the introduction of the spaceship operator, which you can use to quickly and conveniently compare two expressions. Use this operator as follows:

a <=> b

  • If a is less than b, this expression outputs -1
  • If a is equal to b, this expression outputs 0
  • If a is greater than b, this expression outputs 1

Using this operator to compare variables requires much less typing than coding multiple tests with the traditional less than (<), equal to (==) and (>) greater than operators do.

Other Syntax Changes

Many other minor aspects of PHP syntax have also changed in the transition from PHP 5.6 to PHP 7. The following modifications are backward incompatible, which means that developers who have previously worked in PHP 5.6 will need to update their code if they want it to work under PHP 7.

  • Old-fashioned error handling has been replaced with object-oriented exceptions. This change is intended to make it easier for developers to find and fix bugs in their code.
  • Syntax for variable dereferencing has been changed to make it more consistent.
  • Syntax for the foreach statement has changed.
  • The list() operator no longer supports strings.
  • In PHP 5.6, a bug allowed the switch statement to have multiple default clauses, leading to code behaving unpredictably. This bug has now been fixed.
  • PHP 7 features more consistent conversions between integers and floating point numbers. This change eliminates some surprising errors that can occur when you intentionally or accidentally convert a variable that was initially stored as an integer into a floating point number, which is not necessarily a whole number, or a floating point into an integer.
  • The old-fashioned syntax for marking comments in INI files has been removed. Instead of prefixing comments with the # symbol, you now need to use a semi-colon instead.

To see details of other backward-incomptable changes that have been introduced in PHP 7, visit PHP.net to download the documentation for the new language version. This documentation explains the technical advances that appear in PHP 7 in detail and can be a useful reference manual for developers who are programming in PHP 7 for the first time. For a quick look at the new features in PHP 7, take a look at this summary.

How Do I Upgrade to PHP 7?

PHP 7 is the most significant update that has affected the PHP scripting language in more than a decade. Therefore, upgrading existing code to PHP 7 comes with a few challenges. However, the reward — much faster performance and less overall demand on your web servers — is worth the effort of upgrading.

First, you need to make sure that any libraries that your PHP project uses are available for PHP 7. If the libraries do not yet support PHP 7, you may have to hold off on upgrading for a while, or see if it is possible to remove dependence on those libraries.

If your code is written in PHP 5.5 or PHP 5.6, then upgrading will likely be straightforward. However, if you use PHP 4, then there are some syntax changes that you should be aware of. For example, the old style of constructor functions employed in PHP 4 is not supported in PHP 7, even though these constructors worked in PHP 5.

When upgrading to PHP 7, it is best to ensure that your code includes tests, such as unit and integration tests. These tests should catch any issues with your application before they show up as bugs in a live environment.

Who Is Already Using PHP 7?

As of December 2015, less than 0.1 percent of websites are using PHP 7. However, many sites are expected to upgrade soon, as PHP 7’s clear performance advantages mean that it is sure to play a role in the future of web development. WordPress, the popular website-building platform used by millions of small businesses and bloggers, has been preparing for the release of PHP 7 for months, which means that WordPress users can easily upgrade to the new version of the language.

Conclusion

PHP 7 is a major upgrade compared to the last stable version of the language, PHP 5.6. Although upgrading your code from PHP 5.6 to PHP 7 involves carefully checking for incompatibilities, both in your code and in any libraries on which your code depends on, the benefits of upgrading to PHP 7 make the effort very worthwhile. PHP 7 performs much faster than PHP 5.6, which allows sites that use the new version of the language to offer much better service to their users.

PHP Microframework vs. Full Stack Framework

Think back to the hazy days of early web-page development on the Internet. You saw many pages hand-coded in HTML — dynamic pages that could produce and display different content to customize a visitor’s experience were just a dream in a programmer’s eye. Then the first server development environments like WebBase began to emerge. “PHP,” — the “hypertext preprocessor” script — ColdFusion and Microsoft’s “ASP” programming tools came out to help create dynamic, modular websites. Full-stack frameworks finally appeared on the horizon, providing multiple libraries in one package. Popular web-application framework environments went on to include web2py, Ruby on Rails, Django, and ASP.NET.

The Rise of Micro-Frameworks

Over time, full-stack frameworks grew ever bigger to handle the increasingly large and complex websites appearing across the online world. The downside of this growth is they became too difficult to develop simple projects, and you had too much overhead for rapid development.

In response to these challenges, engineers developed micro-frameworks. For smaller projects and specific-use cases, these stripped-down frameworks were easier to implement and provided faster testing and deployment.

Today you have a wide variety of full-stack and micro-PHP environments to choose from. Let’s take a closer look at the advantages and disadvantages of each one while examining some of the most successful packages.

PHP Micro-Framework vs. Full-Stack Framework

Full-stack frameworks assist programmers with the entire development stack from interfacing with the user to the data store. Anything outside of a full-stack framework is technically a “nonfull-stack framework.” Of that group, if the framework and libraries are smaller than “5k,” or 5,000 lines of code, it is known as a micro-framework.

Micro-frameworks leave out many of the components of a full-stack setup, including:

  • Web template engine

  • Input validation

  • Database abstraction

  • Roles, accounts, and authentication

Full-stack frameworks are like driving a huge, fully-equipped SUV compared to a stick-shift sports car. The full-stack framework has a plethora of features and options, but it can be cumbersome and slow. While micro-frameworks have fewer features, they also carry the advantages of being light, quick and nimble.

Full-stack frameworks function against themselves in that they can do many things — with the result that they do few things well. Micro-frameworks do fewer things well, but you may need to use multiple frameworks, and they do not always get along well.

When To Deploy Micro-Frameworks or Full-Stack Frameworks

If you have a small project and need specific features quickly, a micro-framework may be your best bet. For medium to large projects with more demands, a full-stack framework will work better.

Full-stack frameworks have everything you need. However, the way they do things and how they structure projects is not very flexible. Micro-frameworks have more flexibility and leave more decisions up to you.

However, one of the misconceptions about micro-frameworks is that they are only for small projects. It simply means that the framework does not have all of the components you’ll find in a full-stack environment. Micro-frameworks do not have all of the helpers, libraries and structures of the full-stack frameworks, but sometimes it is easier to focus on a specific challenge without worrying about which libraries you need.

A disadvantage of micro-frameworks is that when projects grow much bigger, the micro-framework may not have the features required to accommodate that growth. On the other hand, you get lots of flexibility.

For example, if you use a full-stack library in the beginning with the anticipation that the project will grow, you are still “married” to the libraries the full-stack framework provides, and they will not always be the best options for the project. An ideal middle ground might be to create the project out of one micro-framework in the beginning. Then you can split that framework and add additional ones as the project evolves.

PHP Full-Stack and Micro-Framework Examples

With almost 80 percent of servers on the Internet using PHP code in some capacity, PHP frameworks are popular and useful tools. Here the top five PHP full-stack and micro-frameworks in use today:

Here are Five Great Full-Stack PHP Frameworks for You:

1. Laravel

Laravel is one of the most popular PHP frameworks used today. It has a supportive community and an extensive ecosystem of tutorials and resources. A free, open-source framework, it has a powerful packaging system, various options for accessing databases and some useful utilities to deploy and maintain applications. Taylor Orwell developed it in 2011 to overcome weaknesses he saw in the CodeIgniter web application framework.

2. CakePHP

An open-source framework, CakePHP resembles Ruby on Rails, a popular web application framework. Developed back in April of 2005, it was a leading framework for many years. CakePHP has worked hard to stay updated, and companies using it include fashion brand Express, Hyundai, and BMW.

3. Zend Framework

Zend Framework has been in existence for almost ten years. An open-source project, it is a favorite of multi-national companies such as Cisco and BBC. Many of the people behind Zend Framework were developers of PHP. While powerful, Zend Framework is hard to learn and has a confusing array of configuration options — over time the project grew more complicated with many layers of classes developers found difficult to grasp.

4. Phalcon

If you feel the “need for speed,” Phalcon is for you. Phalcon is different from other frameworks in that it is an extension written in C. This approach allows it to increase execution speed and decrease the use of resources.

Phalcon 2.0, released in April 2015, used the Zephir coding language — it is probably the fastest entry in our list. Released in 2012, Phalcon was originally the product of Andres Gutierrez and various colleagues searching for a different way of approaching traditional PHP web application frameworks. Phalcon is:

  • Simple to learn, so it is a good choice for experienced and beginner developers alike.

  • Feature-rich to develop a broad variety of web applications.

  • Popular among PHP developers.

  • Rapidly increasing in popularity since it debuted in 2012.

5. Symfony

Symfony is a reliable choice for large-scale projects. Using Ruby on Rails, Spring, and Django as inspirations, Symfony uses a system of reusable components. Developed by Sensiolabs, Symfony first appeared on the scene in 2005. An open-source PHP framework, it utilizes large parts of other PHP projects including:

  • Swift Mailer, a library for emails.

  • PHPUnit, a framework for testing units.

Its components are in some of the most successful projects online, including content-management system Drupal and the Twig templating engine.

Here are Five Micro-PHP Frameworks You Should Try:

1. Lumen

The team behind Laravel developed Lumen. If you are familiar with Laravel, then Lumen provides an easy transition to micro-frameworks. Designed by Taylor Otwell in 2014, it allows you to use many Laravel components such as “middleware,” validation, caching and the Laravel service container.

2. Slim

Slim is one of the most popular PHP microframeworks — it has more than 960,000 installs and came in 15th in a SitePoint survey of the top PHP frameworks of 2015. It features a powerful router, simple request and response abstractions, plenty of helper methods for easier caching, and session support. Josh Lockhart designed Slim, and he is also the author of the popular books “Modern PHP” and “PHP the Right Way.”

3. Silex

Introduced in September of 2010, Fabien Potencier and Igor Wiedler created Silex, based on Symfony and the Twig template engine. Silex is extremely lightweight and lets you add features as needed. Originally built to handle small projects, you can extend it into a full “MVC,” or model-view-controller, framework by choosing between two versions:

Fat: Comes with all features, a template engine and database abstraction.

Slim: Only includes a routing engine.

4. Wave

Wave separates itself from the competition due to its application-programming interface, or “API,” handler functionality that comes integrated into the framework. Developed in 2012 by Kristo Vaher, an Estonian developer, Wave is very lean, offering only the most common features required. Also, it has extensive documentation that is helpful for new learners. It comes complete with a gateway for clean URLs and a view controller.

5. Phalcon

The micro-stack version of the full-stack Phalcon framework, it is one of the fastest-growing PHP micro-stacks for the same reasons that its big brother is making so many waves in the PHP community. The original Phalcon came out in 2005 from Columbian developer Andres Gutierrez, a 2012 TR35 winner. Micro-stack Phalcon is the fastest micro-framework available due to its implementation as an extension in C. However, Phalcon does not have much community support and lacks thorough third-party documentation.

Decision Time: Full-Stack or Micro-Stack?

As you can see, there are lots of choices in PHP frameworks. When is it appropriate to use one selection over the other? Micro-frameworks are better for smaller projects that require simplicity, low overhead, and rapid deployment.

On the other hand, large website projects with many moving parts demand the robust libraries and powerful components of a full-stack framework. If you are creating an enormous application like a social-media or large e-commerce website with a global footprint, you have to use the strength and depth of a full-stack framework.

Experienced developers can get away with beginning a project on micro-frameworks and then adding additional micro-frameworks when needed. It is an attractive option, but beginner and intermediate developers should avoid this path.

The definitive answer is, “It depends.” In addition to the requirements of the project, constraints of budget, time, server architecture and programmer familiarity with the framework all come into play. The best option is to test various packages and determine through experience which option is right for your project.

Comparing PHP 7 vs. HHVM

PHP is one of the most popular scripting languages used for web development. The latest version of PHP, PHP 7 is a new version of the language that is been optimized for fast performance. However, PHP has a rival in HHVM (Hip Hop Virtual Machine) — a virtual tool that executes PHP code. The competition between these two options is heating up, so let’s take a look at the performance that each can offer.

What is HHVM?

In 2008, Facebook started working on a tool to convert PHP script into C++ so it could be compiled and executed on web servers. The aim was to conserve server resources, an important goal, as Facebook’s user base was growing rapidly. In this sense, the project was a success; it allowed the server to accommodate between five and six times more traffic than it had managed before.

Fast-forward a couple years to 2010. Facebook’s server needs had grown even more, placing it in a position to require another innovation to allow it to operate more efficiently. In response to this demand, Facebook developed the Hip Hop Virtual Machine (HHVM).

HHVM uses Just-In-Time (JIT) compilation to convert PHP code into a type of bytecode. It then converts this bytecode into machine code and optimizes it so that it runs as quickly as possible.

What is PHP 7?

PHP 7 is the PHP community’s response to HHVM. Early announcements of the launch of PHP 7 claimed that it would offer better than 100 percent performance improvements over the previous version of the language, PHP 5.

You might be wondering why PHP skipped version 6. The answer is that development on PHP 6 began in 2005, but it went on so long and ran into so many problems that PHP 6 had developed a bad reputation long before it was ready for release. As a result, the PHP community decided to skip the name PHP 6 and go straight to PHP 7 for the new working version of the language.

The real question is not how PHP 7 compares to PHP 5, as it is pretty clear that PHP 7 offers speedier performance. Instead, the consideration is how PHP 7 compares to HHVM. Many experts have conducted tests on the two ways of handling PHP code, which have revealed some interesting results.

PHP 7 vs. HHVM: Similarities and Differences

Before answering the “which is better” question, let’s take a look at the key differences between PHP 7 and HHVM, as well as the ways in which they are similar.

Code Interpretation

The fundamental difference between PHP 7 and HHVM is the way in which each one interprets PHP code. PHP 7 uses the standard PHP interpreter, free software that is available for anyone to use, to directly interpret and execute PHP code on the server. This generates HTML code, which is then sent to the client. The client then displays the desired content to the web user.

In contrast, the Hip Hop Virtual Machine first converts PHP code into Hip Hop bytecode. This code is then translated into machine code and executed. Some optimization takes place during this translation, ironing out inefficiencies in PHP code with the aim of delivering faster performance.

Writing Code

Both the PHP interpreter and HHVM take PHP code and execute it. Therefore, the process of writing the code is pretty much the same in each case. However, if you want to use HHVM, you need to install it on your server and then call it using the hhvm command on the command line.

Benchmark Testing

HHVM has offered much faster performance than previous versions of PHP. However, recent benchmark tests suggest that PHP 7 is slightly faster than HHVM, at least in some situations. Let’s take a look at the results of some benchmark testing conducted by Kinsta.

  • WordPress: Running on WordPress 4.1.1, PHP 7 allows more than twice as many requests to be executed per second as PHP 5.6. However, it still doesn’t process quite as many as HHVM 3.6.1, which executed 624 requests per second in the test compared to just 604 executed each second by PHP 7.

  • Drupal: PHP 7 offers a distinct advantage over HHVM for Drupal users. PHP 7 can handle 37 percent more server requests per second compared to HHVM on Drupal 8.

Which Companies Use HHVM?

In addition to Facebook, which developed HHVM, many other businesses have adopted this solution to running PHP applications on their own servers. These include Wikimedia and the e-commerce site Etsy.

  • Wikimedia: Wikimedia hosts a huge range of educational content, including the famous Wikipedia online encyclopedia. Attracting nearly half a billion Internet users each month, Wikimedia needs to optimize server performance to cope with its high level of demand. HHVM poses a significant advantage over PHP in that it can load multiple SPU cores simultaneously whereas PHP is a single-threaded language that can’t be parallelized. According to Wikimedia, deploying HHVM shrank CPU load from 50 to just 10 percent, halved the mean time taken to respond to users submitting edits and reduced the average page load time from 1.3 seconds to just 0.9 seconds.

  • Etsy: With 54 million users, Etsy’s servers also face significant demands. Etsy engineers compared HHVM to PHP 5.4 and found that HHVM could cope with up to 280 server requests per second whereas the response time of PHP 5.4 started to dramatically increase once the number of requests grew beyond 190 per second.

What Does the Future Hold for PHP 7 and HHVM?

PHP 7 is due for stable release in November 2015. Therefore, companies are not yet using the new language, but promising benchmark test results of the performance of the beta version of PHP 7 could tempt more companies to adopt the new version of the language.

The future looks bright for PHP 7, but what about HHVM? It is likely that it is far from dead. Many businesses are already using HHVM to increase performance on their sites. The transition between PHP and HHVM is not instantaneous. It took Etsy more than six months to complete the transition. With the speed benefits of PHP 7 compared to HHVM being only very slight, it is unlikely that businesses will rush to switch back to PHP.

Facebook is continuing to develop HHVM. It has recently announced support for Mac OS X, making the technology accessible for developers who prefer to work in the Apple development environment. HHVM developers are convinced that HHVM is still faster than PHP 7 in many situations, including with WordPress.

Why Does the HHVM vs. PHP 7 Competition Matter to PHP Shop Owners?

As an online store owner, you need to make your decision on whether to use PHP 7 or HHVM based on the platform that hosts your shop. For example, if your site is built using WordPress, take a look at benchmark tests for HHVM and PHP 7 to find out how the latest release of each one performs. You want to choose the solution that can offer the biggest reduction in page load times, server response times and CPU usage.

Reasons to Choose HHVM

  • HHVM uses dynamic translation to deliver faster performance in many situations, including on WordPress.

  • HHVM uses less memory to process each request in cases where it faces a very large number of requests.

  • HHVM developers are steadily increasing the number of PHP code bases that the engine can run. It can already run the latest version of WordPress, along with many other common PHP frameworks and applications.

  • HHVM is open source. Even though HHVM has been developed by Facebook, it is open source, which means the source code is available to anyone who wants to use or alter it.

Reasons to Choose PHP 7

  • PHP 7 performs faster than HHVM in some situations, including when running on Drupal 8.

  • Using PHP 7 doesn’t require you to install or setup HHVM.

  • Code written in PHP 5 should work as expected after a transition to PHP 7, although some features of PHP 4 code are no longer supported in the new release. In practice, this means that any code created in the last decade is probably ready for the transition to PHP 7.

  • PHP 7 is developed by the PHP community, a group with a long-standing reputation for creating stable and reliable PHP releases.

HHVM vs. PHP 7: Make Your Choice

Don’t agonize for too long over the decision. Kinsta recommends that online businesses choose quickly between PHP 7 and HHVM. The sooner you make your decision, the sooner you can begin to implement the solution, allowing you to optimize your website performance. A poorly performing website can cause your reputation to suffer, which can be difficult to reverse.

Both HHVM and PHP 7 offer significant benefits compared to older versions of PHP. Make your choice and start the process of switching your site to the new system as soon as possible.

Top 5 PHP APM Tips & Tricks

This article series has covered a lot of ground: it presented an overview of application performance management (APM), it identified the challenges in implementing an APM strategy, it proposed a top-5 list of important metrics to measure to assess the health of an enterprise PHP application, and it presented AppDynamics’ approach to building an APM solution. In this final installment this article provides some tips-and-tricks to help you implement an optimal APM strategy. Specifically, this article addresses the following topics:

  • Business Transaction Optimization

  • Snapshot Tuning

  • Threshold Tuning

  • Tier Management

  • Capturing Contextual Information

Business Transaction Optimization

Over and over throughout this article series I have been emphasizing the importance of business transactions to your monitoring solution. To get the most out of your business transaction monitoring, however, you need to do a few times:

  • Properly name your business transactions to match your business functions

  • Properly identify your business transactions

  • Reduce noise by excluding business transactions that you do not care about

AppDynamics will automatically identify business transactions for you and try to name them the best that it can, but depending on how your application is written, these names may or may not be reflective of the business transactions themselves. For example, you may have a business transaction identified as “POST /payment” that equates to your checkout flow. In this case, it is going to be easier for your operations staff, as well as when generating reports that you might share with executives, if business transactions names reflect their business function. So consider renaming this business transaction to “Checkout”.

Next, if you have multiple business transactions that are identified by a single entry-point, take the time to break those into individual business transactions. There are several examples where this might happen, which include the following:

  • URLs that route to the same MVC controller and action

  • Business Transactions that determine their function based on their payload

  • Business Transactions that determine their function based on GET parameters

  • Complex URI paths

If a single entry-point corresponds to multiple business functions then configure the business transactions based on the differentiating criteria. For example, if the body of an HTTP POST has an “operation” element that identifies the operation to perform then break the transaction based on that operation. Or if there is an “execute” action that accepts a “command” URI argument, then break the transaction based on the “command” segment. Finally, URI patterns can vary from application to application, so it is important for you to choose the one that best matches your application. For example, AppDynamics automatically defines business transactions for URIs based on two segments, such as /one/two. For most PHP MVC frameworks, this automatically routes to the application controller and action. If your application uses one segment or if it uses four segments, then you need to define your business transactions based on your naming convention.

Naming and identifying business transactions is important to ensuring that you’re capturing the correct business functionality, but it is equally important to exclude as much noise as possible. Do you have any business transactions that you really do not care about? For example, is there a web game that checks high scores every couple minutes? Or is there a PHP CLI cron job that runs every night, takes a long time, but because it is offline and does not impact the end user, you do not care? If so then exclude these transactions so that they do not add noise to your analysis.

Snapshot Tuning

As mentioned in the previous article, AppDynamics intelligently captures performance snapshots by both profiling PHP code executions at a specified interval instead of leveraging code instrumentation for all snapshot elements, and by limiting the number of snapshots captured in a performance session. Because both of these values can be tuned, it can benefit you to tune them.

Out-of-the-box, AppDynamics captures the entire stack trace while trimming any granularity below the configured threshold. If you are only interested in “big” performance problems then you may not require granularity as fine as 10 milliseconds. You can increase this interval to 50 milliseconds, but you will lose granularity. If you are finely tuning your application then you may want 10-millisecond granularity, but if you have no intention of tuning methods that execute in under 50 milliseconds, then why do you need that level of granularity? The point is that you should analyze your requirements and tune accordingly.

Next, observe your production troubleshooting patterns and determine whether or not the number of snapshots that AppDynamics captures is appropriate for your situation. If you find that, while capturing up to 5 snapshots every minute for 5 minutes is resulting in 20 or more snapshots, but you only ever review 2 of those snapshots then do not bother capturing 20. Try configuring AppDynamics to capture up to 1 snapshot every minute for 5 minutes. And if you’re only interested in systemic problems then you can turn down the maximum number of attempts to 5. This will significantly reduce that constant overhead, but at the cost of possibly not capturing a representative snapshot.

Threshold Tuning

AppDynamics has designed a generic monitoring solution and, as such, it defaults to alerting to business transactions that are slower than two standard deviations from normal. This works well in most circumstances, but you need to identify how volatile your application response times are to determine whether or not this is the best configuration for your business needs.

AppDynamics defines three types of thresholds against which business transactions are evaluated with their baselines:

  • Standard Deviation: compares the response time of a business transaction against a number of standard deviations from its baseline

  • Percentage: compares the response time of a business transaction against a percentage of difference from baseline

  • Static SLAs: compares the response time of a business transaction against a static value, such as 2 seconds

If your application response times are volatile, then the default threshold of two standard deviations might result in too many false alerts. In this case you might want to increase this to more standard deviations or even switch to another strategy. If your application response times have low volatility then you might want to decrease your thresholds to alert you to problems sooner.  Furthermore, if you have services or APIs that you provide to users that have specific SLAs then you should setup a static SLA value for that business transaction. AppDynamics provides you with the flexibility of defining alerting rules generally or on individual business transactions.

You need to analyze your application behavior and configure the alerting engine accordingly.

Tier Management

I’ve described how AppDynamics captures baselines for business transactions, but it also captures baselines for business transactions across tiers. For example, if your business transaction calls a rules engine service tier then AppDynamics will capture the number of calls and the average response time for that tier as a contributor to the business transaction baseline. Therefore, you want to ensure that all of your tiers are clearly identified.

Out of the box, AppDynamics identifies tiers across common protocols, such as HTTP, PHP CLI, PHP MVC, and so forth. For example, if it sees you make a database call then it assumes that there is a database and allocates the time spent in the method call to the database. This is important because you don’t want to think that you have a very slow “save” method in a ORM class, instead you want to know how long it takes to persist your object to the database and attribute that time to the database.

AppDynamics does a good job of identifying tiers that follow common protocols, but there are times when you’re communication with a back-end system does not use a common protocol. For example, I was working at an insurance company that used an AS/400 for quoting. We leveraged a library that used a proprietary socket protocol to make a connection to the server. Obviously AppDynamics would know nothing about that socket connection and how it was being used, so the answer to our problem was to identify the method call that makes the connection to the AS/400 and identify it as a custom back-end resource.  When you do this, AppDynamics treats that method call as a tier and counts the number of calls and captures the average response time of that method execution.

You might be able to use the out of the box functionality, but if you have special requirements then AppDynamics provides a mechanism that allows you to manually define your application tiers by using the PHP API functions to further tailor your application.

Capturing Contextual Information

When performance problems occur, they are sometimes limited to a specific browser or mobile device, or they may only occur based on input associated with a request. If the problem is not systemic (across all of your servers), then how do you identify the subset of requests that are causing the problem?

The answer is that you need to capture context-specific information in your snapshots so that you can look for commonalities. These might include:

  • HTTP headers, such as browser type (user-agent), cookies, or referrer

  • HTTP GET parameter values

  • Method parameter values

  • Application variables and their values

Think about all of the pieces of information that you might need to troubleshoot and isolate a subset of poor performing PHP transactions. For example, if you capture the User-Agent HTTP header then you can know the browser that the user was using to execute your business transaction. If your HTTP request accepts GET parameters, such as a search string, then you might want to see the value of one or more of those parameters, e.g. what was the user searching for? Additionally, if you have code-level understanding about how your application works, you might want to see the values of specific method parameters.

AppDynamics can be configured to capture contextual information and add it to snapshots, which can include all of the aforementioned types of values. The process can be summarized as follow:

  1. AppDynamics observes that a business transaction is running slow

  2. It triggers the capture of a session of snapshots

  3. On each snapshot, it captures the contextual information that you requested and associates it with the snapshot

The result is that when you find a snapshot illustrating the problem, you can review this contextual information to see if it provides you with more diagnostic information.

The only warning is that this comes at a small price: AppDynamics uses code instrumentation to capture the values of methods parameters. In other words, use this functionality where you need to, but use it sparingly.

Conclusion

Application Performance Management (APM) is a challenge that balances the richness of data and the ability to diagnose the root cause of PHP performance problems with minimum overhead required to capture that data. There are configuration options and tuning capabilities that you can employ to provide you with the information you need while minimizing the amount of overhead on your application. This article reviewed a few core tips and tricks that anyone implementing an APM strategy should consider. Specifically it presented recommendations about the following:

  • Business Transaction Optimization

  • Snapshot Tuning

  • Threshold Tuning

  • Tier Management

  • Capturing Contextual Information

APM is not easy, but tools like AppDynamics make it easy for you to capture the information you need while reducing the impact to your production applications.

Top 5 Performance Metrics to Capture in Enterprise PHP Applications

The last couple articles presented an introduction to Application Performance Management (APM) and identified the challenges in effectively implementing an APM strategy. This article builds on these topics by reviewing five of the top performance metrics to capture to assess the health of your enterprise PHP application.

Specifically this article reviews the following:

  • Business Transactions

  • Internal Dependencies

  • External Calls

  • Caching Strategy

  • Application Topology

1. Business Transactions

Business Transactions provide insight into real-user behavior: they capture real-time performance that real users are experiencing as they interact with your application. As mentioned in the previous article, measuring the performance of a business transaction involves capturing the response time of a business transaction holistically as well as measuring the response times of its constituent tiers. These response times can then be compared with the baseline that best meets your business needs to determine normalcy.

If you were to measure only a single aspect of your application I would encourage you to measure the behavior of your business transactions. While container metrics can provide a wealth of information and can help you determine when to auto-scale your environment, your business transactions determine the performance of your application. Instead of asking for the CPU usage of your application server you should be asking whether or not your users are able to complete their business transactions and if those business transactions are behaving normally.

As a little background, business transactions are identified by their entry-point, which is the interaction with your application that starts the business transaction. In the case of a PHP application, this is usually the HTTP request. There may be some exceptions, such as PHP CLI, in which case the business transaction could be a PHP script executed by a cron job from the command line. In the case of a PHP worker server, the business transaction could potentially be the job that the PHP application executes that it picked up from a queue server. Alternatively, you may choose to define multiple entry-points for the same web request based on a URL parameter or for a service call based on the contents of its body. The point is that the business transaction needs to be related to a function that means something to your business.

Once a business transaction is identified, its performance is measured across your entire application ecosystem. The performance of each individual business transaction is evaluated against its baseline to assess normalcy. For example, we might determine that if the response time of the business transaction is slower than two standard deviations from the average response time for this baseline that it is behaving abnormally, as shown in figure 1.

Figure 1 Evaluating BT Response Time Against its Baseline

The baseline used to evaluate the business transaction is evaluated is consistent for the hour in which the business transaction is running, but the business transaction is being refined by each business transaction execution. For example, if you have chosen a baseline that compares business transactions against the average response time for the hour of day and the day of the week, after the current hour is over, all business transactions executed in that hour will be incorporated into the baseline for next week. Through this mechanism an application can evolve over time without requiring the original baseline to be thrown away and rebuilt; you can consider it as a window moving over time.

In summary, business transactions are the most reflective measurement of the user experience so they are the most important metric to capture.

2. Internal Dependencies

Your PHP application may be utilizing a backend database, a caching layer, or possibly even a queue server as it offloads I/O intensive blocking tasks onto worker servers to process in the background. Whatever the backend your PHP application interfaces with, the latency to these backend services can affect the performance of your PHP application performance. The various types of internal exit calls may include:

  • SQL databases

  • NoSQL servers

  • In-memory cache

  • Internal services

  • Queue servers

In some environments, your PHP application may be interfacing with an obscure backend or messaging/queue server. For example, you may have an old message broker serving as an interface between your PHP application and other applications. While this message broker may be outdated, it is nevertheless part of an older architecture and is part of the ecosystem in which your distributed applications communicate with. Even if your APM solution does not autodiscover the messaging server, you may build additional instrumentation to detect the messaging server and measure the latency. If you want to draw correlation so the business transaction does not become fragmented, you may also build additional instrumentation so that the correlation is autocompleted when the request passes through the messaging server to the applications on the other side of the queue.

From a business transaction perspective, we can identify and measure internal dependencies as being in their own tiers. Sometimes we need to configure the monitoring solution to identify methods that really wrap external service calls, but for common protocols, such as HTTP and CLI, internal dependencies can be automatically detected. Similar to business transactions and their constituent application tiers, external dependency behavior should be baselined and response times evaluated against those baselines.

However your PHP application communicates with internal services, the latency in waiting for the response can potentially impact the performance of your application and your customer experience. Measuring and optimizing the response time if your communications can help solve for these bottlenecks.

3. External Calls

In addition to your internal services and backends, exit calls may also include remote third-party web service APIs that your application makes calls to in real-time. For example, if your customer is attempting to purchase items in a shopping cart and in order for the transaction to complete your application must charge their credit card so that you can display a confirmation or error page. This is an example of a blocking exit call because your entire transaction is now dependent on the response of that call being made to your third-party merchant provider that is charging the credit card. If the customers credit card was charged successfully, the user is presented with a confirmation page and a receipt. If the credit card was declined, the user is presented with an error message to try again. Regardless, the customer is waiting on the application that is dependent on the third party merchant provider. The latency of the exit call will have an immediate impact on the performance of this particular instance.

External dependencies can come in various forms and are systems with which your application interacts. We do not necessarily have control over the code running inside external dependencies, but we often have control over the configuration of those external dependencies, so it is important to know when they are running well and when they are not. Furthermore, we need to be able to differentiate between problems in our application and problems in dependencies.

Business transactions provide you with the best holistic view of the performance of your application and can help you triage performance issues, but external dependencies can significantly affect your applications in unexpected ways unless you are watching them.

4. Caching Strategy

It is always faster to serve an object from memory than it is to make a network call to retrieve the object from a system like a database; caches provide a mechanism for storing object instances locally to avoid this network round trip. But caches can present their own performance challenges if they are not properly configured. Common caching problems include:

  • Loading too much data into the cache

  • Not properly sizing the cache

When measuring the performance of a cache, you need to identify the number of objects loaded into the cache and then track the percentage of those objects that are being used. The key metrics to look at are the cache hit ratio and the number of objects that are being ejected from the cache. The cache hit count, or hit ratio, reports the number of object requests that are served from cache rather than requiring a network trip to retrieve the object. If the cache is huge, the hit ratio is tiny (under 10% or 20%), and you are not seeing many objects ejected from the cache then this is an indicator that you are loading too much data into the cache. In other words, your cache is large enough that it is not thrashing (see below) and contains a lot of data that is not being used.

The other aspect to consider when measuring cache performance is the cache size. Is the cache too large, as in the previous example? Is the cache too small? Or is the cache sized appropriately?

A common problem when sizing a cache is not properly anticipating user behavior and how the cache will be used. Let’s consider an APC cache configured to use 32M of memory. If 32M is not enough for APC to be used as an opcode cache, then you run the risk of exchanging data in memory for data on the disk. Considering disk I/O is much slower than reading from memory, this defeats the purpose of your in-memory cache and significantly slows down your application performance. The result is that we’re spending more time managing the cache rather than serving objects: in this scenario the cache is actually getting in the way rather than improving performance.

When you size a cache too small and the aforementioned behavior occurs, we say that the cache is thrashing and in this scenario it is almost better to have no cache than a thrashing cache. Figure 2 attempts to show this graphically.

Figure 2 Cache Thrashing

In this situation, the application requests an object from the cache, but the object is not found. It then queries the external resource across the network for the object and adds it to the cache. Finally, the cache is full so it needs to choose an object to eject from the cache to make room for the new object and then add the new object to the cache.

5. Application Topology

The final performance component to measure in this top-5 list is your application topology. Because of the advent of the cloud, applications can now be elastic in nature: your application environment can grow and shrink to meet your user demand. Therefore, it is important to take an inventory of your application topology to determine whether or not your environment is sized optimally. If you have too many virtual server instances then your cloud-hosting cost is going to go up, but if you do not have enough then your business transactions are going to suffer.

It is important to measure two metrics during this assessment:

  • Business Transaction Load

  • Container Performance

Business transactions should be baselined and you should know at any given time the number of servers needed to satisfy your baseline.  If your business transaction load increases unexpectedly, such as to more than two times the standard deviation of normal load then you may want to add additional servers to satisfy those users.

The other metric to measure is the performance of your containers. Specifically you want to determine if any tiers of servers are under duress and, if they are, you may want to add additional servers to that tier. It is important to look at the servers across a tier because an individual server may be under duress due to factors like garbage collection, but if a large percentage of servers in a tier are under duress then it may indicate that the tier cannot support the load it is receiving.

Because your application components can scale individually, it is important to analyze the performance of each application component and adjust your topology accordingly.

Conclusion

This article presented a top-5 list of metrics that you might want to measure when assessing the health of your application. In summary, those top-5 items were:

  • Business Transactions

  • External Dependencies

  • Caching Strategy

  • Exit Calls

  • Application Topology

In the next article we’re going to pull all of the topics in this series together to present the approach that AppDynamics took to implementing its APM strategy. This is not a marketing article, but rather an explanation of why certain decisions and optimizations were made and how they can provide you with a powerful view of the health of a virtual or cloud-based application.