Your SlideShare is downloading. ×
Tuning PHP for Windows & IIS
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Tuning PHP for Windows & IIS

9,838
views

Published on

Mark Brown's talk at Dutch PHP Conference 2011 for tuning PHP on Windows and IIS.

Mark Brown's talk at Dutch PHP Conference 2011 for tuning PHP on Windows and IIS.

Published in: Technology

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
9,838
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
44
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • http://learn.iis.net/page.aspx/728/best-practices-for-php-on-the-microsoft-web-platform/
  • Fast CGIWith the release of FastCGI first time you could actually consider hosting php on win/iis, production quality, no more crashes.Previously you had two options to host PHP, CGI or PHP ISAPI.CGI was stable but very slow because you had to spin up a new process for each new PHP request.ISAPI was faster but since many popular extensions for PHP were not thread safe this caused major issues with stability.FastCGI handles PHP requests out of an app pool rather than spinning up a new one each time.FastCGI provides optimal PHP performance without having to manually tune:Fast CGI provides Automatic performance tuning.Determines: CPU usage, memory consumption, context switches. Based upon that information it changes the number of PHP processes to optimize your application automatically. (SetsDynamic Max Instances)Very important if you are a hoster managing many customers since it allows for a higher density of PHP applications on Windows than you could get before or a customer with an app that has large changes in requests over time.Automatic recycling of PHP processes in IIS when php.ini changes. No longer need to restart IIS.Version 1.5 now has a consistent set of features across all versions of IIS. This is important as a significant number of PHP developers still use XP. This will allow them to develop and deploy seamlessly to Windows Server. Version 1.5 of Fast-CGI is included in Windows Server 2008 R2 (IIS 7.5), an update is available for IIS 7 along with a back-port for those using XP.Another useful feature I wanted to point out here as well is you can provide to your customers developing or running PHP on Windows/IIS is the Advanced Logging module in IIS which you can use to consolidate event reporting for PHP itself as well as from IIS. This will help your customers consolidate application performance reporting, good for tracking failed requests or other issues in your php application. No need to have separate error log files for webserver and php.
  • So prior to PHP 5.3 the PHP engine itself wasn’t mature on Windows, causing compatibility and performance problems.Implemented with APR (Apache portable runtime) instead of directly on Win32 created subpar performanceAlso many Windows-specific PHP bugs hadn’t been fixedThere were as I mentioned earlier issues with hosting on IIS itself with the slow CGI or unstable ISAPI handler. Using FastCGI provided the fix for that part.PHP 5.3Has an updated code base, feature and security parity with the rest of PHP.Much of PHP for Windows completely rewritten to use native Win32 instead of through the POSIX layerAlso compiled using our latest compiler VC9 versus VC 6 which was 10 years oldUse the NTS version. No thread safety checks since PHP runs Single threaded on IIS in FastCGI.Reason for NTS is that many of the most popular community extensions themselves are NTS themselves, making NTS the default on Windows is the safest route for stability.The architecture of IIS and the FastCGI extension provide an isolation model that keeps requests separate, removing the need for a thread-safe version. The NTS doesn’t have any of the code that allows PHP to manage multiple threads. As a result, you will see a performance improvement on IIS when using the NTS version as compared to the tread-safe version.
  • Compile and file operations on Windows are slower than on linux. Many more security checks, etc.Many PHP developers on Linux use other caching mechanisms such as memcache or APC.There are no good open source solutions for caching on Windows WinCache is our solution to help provide even more performance for PHP on Windows.Opcode cache – this is a cache of the compiled PHP file. WinCache let PHP core compile the PHP file to generate opcodes first time it is executed. Then caches these opcodes in memory and is shared with other PHP processesIncreasing performance, especially on subsequent access to the executable code. Can expect a 100%-200% increase in performance.File cache – File IO operations on Windows are much more expensive than on Linux. For files on UNC’s or NFS in hosting environments scenarios it is even worse. File Cache stores the contents of opened files in shared memory. This increases performance 80-90% over accessing the files each time from a shared location.Resolve File Path cache – On first access a PHP application will work to determine the absolute path to a file to then open itThis feature is used to store the absolute path from relative file paths used in PHP applications.Again, anything to reduce usage of the file systems calls produces performance gains.Session Cache:The session cache will take and store session data in shared memory cache instead of file system for added performance benefits.Currently this feature cannot be used in a webfarm where there is no session affinity.User Data Cache API’s: Provides caching functions(API’s) with the Can be used by PHP applications for storing variables and objects in shared memory using WinCache instead of PHPs cache.You can cache database data, php data, classes, etc. Overall just closing the feature gap to APC, etc. trying to have a complete solution.WinCache Statistics Script – This thing is very cool and you should check it out. Great for helping you benchmark and fine tune your PHP applications on Windows. Is installed with the WinCache for PHP.PS: this file is protected by default with HTTP basic authentication so if you do provide this for your customers. Just an FYI.
  • Make sure that FastCGI always recycles the php-cgi.exe processes before the native PHP recycling kicks in. The FastCGI process recycling behavior is controlled by the configuration property instanceMaxRequests. This property specifies how many requests the FastCGI process will process before recycling. PHP also has a similar process recycling functionality that is controlled by an environment variable PHP_FCGI_MAX_REQUESTS. By setting instanceMaxRequests to be smaller or equal to PHP_FCGI_MAX_REQUESTS, you can ensure that the native PHP process recycling logic will never kick in.To set:Open FastCGISet instanceMaxRequest to 10000. Click on Environment VariablesCreatePHP_FCGI_MAX_REQUESTS as new variable and set that to 10000 too.If you use PHP Manager this is called out when you first install PHP and open PHP Manager
  • Another reason to be using PHP 5.3 is this is much easier now than it is using 5.2This is very easy to do with PHP 5.3 and IIS 7.Simply install PHP using the Web PI or install Windows binaries from PHP.NET. Select the FastCGI option.For your two websites simple enter in the ini settings you want to override for each site.Once you’re done. Save the php.ini file, and then recycle the application pools for these Web sites for the PHP.INI changes to take effect or if you have set the monitor changes to file set to monitor php.ini it will recycle the app pools for you.
  • Kernel Mode Output cache does not support modules and features that must run in user mode, such as authentication or authorization. Example: If authentication schemes like Basic or Windows authentication are enabled, the cache policy will not work. The content is served but not cached. Troubleshooting Output Caching:Failed Request Event Buffering (FREB) is the best way to find out whether or not your request gets cached. FREB tells you why something does not get cached. Here is a sample of a FREB log. In this case, the HTTPSYS_CACHEABLE event tells you that the request does not get cached because the kernel-mode cache is not enabled. Use this to show what is cached in kernel mode.netsh http show cachestatehttp://learn.iis.net/page.aspx/154/walkthrough-iis-70-output-caching/
  • When a user hits your site www.mysite.com IIS will go through the list of default documents for that site. This is inheirited from the server itself. It will cycle through each of them until it finds the correct one for your site. Set the default document for our site to whatever it should be for your php site. Generally this is index.php. This will short circuit this step and send users directly to the default document.Remove unused processes and services from your webserver, mail apps, anti-virus, screen savers, etc. This is just good practice for any webserver.Try to minimize logging on your production site. If you typically have verbose logging in use when you develop, try trimming that down or turning it off. Logging consumes resources.Keep-Alives: The HTTP keep-alive response header improves Web server performance by keeping a client/server connection open across multiple requests to the server. The open connection improves performance when a client makes multiple requests for Web page content, because the server can return the content for each request more quickly. Otherwise, the server has to open a new connection for every request. By default, the HTTP keep-alive response header is enabled in IIS 7. HTTP Compression: One of the most effective ways to reduce the bandwidth needed to deliver the application responses is to use HTTP compression. This can reduce the size of the response by a substantial amount, often by a factor of 10 when applied to easily compressible text content such as HTML. Since compression is based on Content-Encoding negotiation defined in the HTTP 1.1 protocol, enabling it is safe for clients that do not support compression—these clients simply receive an uncompressed version of the content. Dynamic compression usually does not have a prohibitive CPU overhead. In fact, dynamic compression often causes less than 5 percent of the total CPU utilization on a busy server. Dynamic compression can be deployed somewhat liberally to allow for maximum bandwidth savings for any application workloads.
  • When a user hits your site www.mysite.com IIS will go through the list of default documents for that site. This is inheirited from the server itself. It will cycle through each of them until it finds the correct one for your site. Set the default document for our site to whatever it should be for your php site. Generally this is index.php. This will short circuit this step and send users directly to the default document.Remove unused processes and services from your webserver, mail apps, anti-virus, screen savers, etc. This is just good practice for any webserver.Try to minimize logging on your production site. If you typically have verbose logging in use when you develop, try trimming that down or turning it off. Logging consumes resources.Keep-Alives: The HTTP keep-alive response header improves Web server performance by keeping a client/server connection open across multiple requests to the server. The open connection improves performance when a client makes multiple requests for Web page content, because the server can return the content for each request more quickly. Otherwise, the server has to open a new connection for every request. By default, the HTTP keep-alive response header is enabled in IIS 7. HTTP Compression: One of the most effective ways to reduce the bandwidth needed to deliver the application responses is to use HTTP compression. This can reduce the size of the response by a substantial amount, often by a factor of 10 when applied to easily compressible text content such as HTML. Since compression is based on Content-Encoding negotiation defined in the HTTP 1.1 protocol, enabling it is safe for clients that do not support compression—these clients simply receive an uncompressed version of the content. Dynamic compression usually does not have a prohibitive CPU overhead. In fact, dynamic compression often causes less than 5 percent of the total CPU utilization on a busy server. Dynamic compression can be deployed somewhat liberally to allow for maximum bandwidth savings for any application workloads.
  • Transcript

    • 1. Tips & Tricks
      Tuning PHP
      on Windows & IIS
      Mark Brown
      Microsoft Corporation
      mark.brown@microsoft.com
      @markjbrown
    • 2. Tip #1 – Use IIS 7
      PHP on IIS6 and Prior
      CGI – Slow as hell (1 request = 1 process)
      ISAPI – Fast but unstable (mixed threading)
      IIS 7
      Blew up IIS6
      Modular Architecture
      Default Minimum Installation
      Streamlined Processing Pipeline
      Uses FastCGIto handle PHP requests
      FastCGI now available for IIS 6
    • 3. Tip #2 – Use Fast CGI
      Uses an App Pool to process requests
      No CreateProc() for each Request!!!
      App Pool Size is configurable
      Adjust AppPoolSize according to load to maximize response time
      Automatic Tuning Capability
      Set AppPoolSize = 0
      Memory, Context Switches, CPU
      Auto Tuning useful if hosting many sites on same IIS server
      Better density, site only uses resources it needs
    • 4. Tip #3 – Use PHP 5.3
      Feature & Security parity
      Faster File IO on network shares
      Win32 Codebase, not POSIX
      New Windows build scripts
      Compiled with VC9 vs. VC6
      Compile yourself to optimize further
      Non-Thread Safe binary for Windows
      No NTS checks
      Make sure your extensions are NTS too!!!
    • 5. Tip #4 – Use WinCache
      Boost your speed with no code changes
      Opcode Cache
      File Cache
      Stores files in memory
      Relative File Path Cache
      Helpful for shared or NFS storage
      Session Cache
      Enable in php.ini
      User Data Cache
      Store Data in memory
      APC interface
    • 6. Tip 4.5 If !(User Cache)
      MySQL Reverse-Lookup Bug
      FastCGI Bug?
      Follow me on Twitter for updates
      Use mysql_pconnect()
      Can cause issues using temp tables
      [mysqld] section of my.ini
      Add skip-name-resolve
      Use 127.0.0.1 in code
    • 7. Tip #5 – ConfigProc Recycling
      Don’t allow native PHP to do it.
      Allow FastCGI to manage PHP process recycling on IIS.
      Set instanceMaxRequests <= to PHP_FCGI_MAX_REQUESTS
      Default is 10K requests
    • 8. Tip #6 –Per-Site PHP Config
      Only for PHP 5.3
      Configure IIS to have unique PHP config for each site on server.
      Eg. Photo upload site, vs long running scripts
      Php.ini file website overrides
      Insert at the end of php.ini
      [PATH=C:/inetpub/website1.com/] max_execution_time = 300
      [PATH=C:/inetpub/website2.com/] upload_max_filesize = 12M
    • 9. Tip #7 – Use IIS Output Cache
      Use for Semi-Dynamic Content
      Product pages, etc.
      User Mode Caching
      Cached in IIS7 Worker Process
      Authentication and Authorization
      varyByHeadersattribute
      varyByQuerystring attribute
      Kernel Mode Caching
      Cached in HTTP.SYS, a kernel mode driver
      Much faster but lacks features that must execute in Worker Process
    • 10. Tip #8 – Fine Tuning Tips
      Set Default Document (index.php)
      Remove unused services & modules
      Minimize Logging
      Use HTTP Keep-Alives
      Use HTTP Compression
      Static & Dynamic
    • 11. DEMO
    • 12. More Information
      http://php.iis.net
      http://web.ms/php
      http://windows.php.net
      Source Code and WCAT tool:
      http://dl.dropbox.com/u/23010264/PHP_Perf_Win-IIS.zip
    • 13. Thank You
      Questions?