5 easy ways to tune your lamp application _php tutorial

Source: Internet
Author: User
Tags apc common sql injection attacks mysql manual one table drupal mysql slow query log
Introduction

Major web properties such as Wikipedia, Facebook, and Yahoo! Use the LAMP architecture to service millions of of requests per day, while web application software such as Wordpress, Joomla, Drupal, and SugarCRM uses its architecture to make organizations light Deployment of Web-based applications.

The advantage of this architecture lies in its simplicity. While. NET stacks and Java™ technologies can use a lot of hardware, expensive software stacks, and complex performance tuning, the LAMP stack can run on commodity hardware, using an open-source software stack. Because the software stack is a loose set of components rather than a monolithic stack, performance tuning is a challenge because each component needs to be analyzed and tuned.

However, there are several simple performance tasks that can have a huge impact on the performance of any size Web site. In this article, we'll explore 5 of these tasks designed to optimize the performance of LAMP applications. These projects should rarely require architectural changes to your applications, making them a safe and convenient choice for maximizing the responsiveness and hardware requirements of your Web applications.

Using opcode caching

The simplest way to improve the performance of any PHP application (of course, "P" in LAMP) is to use an opcode cache. For any web site I use, it is one of the things I make sure exists, because the performance impact is great (many times there are opcode caches and response times can be reduced by half). But a big question for most people who are unfamiliar with PHP is why the improvements are so great. The answer lies in how PHP handles Web requests. Figure 1 provides an overview of the PHP request process.


Figure 1. PHP Request

Because PHP is an interpreted language, rather than a compiled language such as C or Java, the entire step of parse-compile-execute is performed on each request. You can see why this can be time-consuming and resource-intensive, especially if the script rarely changes between requests. After parsing and compiling the script, the script is in a machine-resolvable state as a series of opcode. This is where opcode caching works. It caches these compilation scripts as a series of opcode to avoid each request step for parsing and compiling. You'll see how this workflow works in Figure 2.

Figure 2. PHP requests Use opcode cache

Therefore, when the php script's cache opcode exists, we can skip the parsing and compiling steps of the PHP request process, execute the cache opcode directly and output the result. The check algorithm is responsible for handling situations where you may have made changes to the script file, so after the first request for the changed script, the script is automatically recompiled and cached for subsequent requests, replacing the cached scripts.

OpCode caching has been popular with PHP for a long time, with some of the early ones dating back to the heyday of PHP V4. There are currently some popular options being actively developed and in use:

    • The alternative PHP cache (APC) may be the most popular opcode cache in PHP (see Resources ). It was developed by a number of core PHP developers and made a big contribution to the speed and stability of Facebook and Yahoo! engineers. It also supports several other speed improvements for handling PHP requests, including a user cache component, which is discussed later in this article.
    • Wincache is an opcode cache that is actively developed primarily by the Microsoft® Internet Information Services (IIS) team for use only on Windows® using the IIS Web server (see resources /c2>). The main motivation for developing it is to make PHP a first-class development platform on the windows-iis-php stack because it is known that APC is not working well on the stack. It is functionally similar to APC, supports a user cache component, and a built-in session handler to take Wincache as a session handler directly.
    • Eaccelerator is a derivation of one of the original PHP caches Turck MMCache opcode cache (see resources ). Unlike APC and Wincache, it is only an opcode cache and optimizer, so it does not contain user cache components. It is fully compatible on the UNIX® and Windows stacks and is popular with sites that do not intend to take advantage of other features offered by APC or Wincache. This is a common scenario if you are using a solution such as memcache to provide a separate user cache server for a multi-Web server environment.

There is no doubt that a opcode cache is the first step in accelerating PHP by eliminating the need to parse and compile scripts after each request. After you complete the first step, you should see improvements in response time and server load. But there's more to optimizing PHP than that, which we'll discuss next.

Optimize your PHP settings

While implementing opcode caching is a great feat of performance improvement, there are a number of other optimization options that you can use to optimize your PHP settings based on the settings in the php.ini file. These settings are more appropriate for production instances, and you may not want to make these changes on a development or test instance because it makes debugging an application problem more difficult.

Let's take a look at some of the items that are important for performance improvement.

Options that should be disabled

There are several php.ini settings that should be disabled because they are commonly used for backward compatibility:

    • register_globals-This feature is often the default value before PHP V4.2, where the incoming request variable is automatically assigned to the normal PHP variable. In addition to causing significant security problems (mixing unfiltered incoming request data with the content of the normal PHP variable), doing so will incur overhead for each request. Disabling this setting makes your application more secure and performance-enhancing.
    • magic_quotes_*-This is another legacy of PHP V4, where incoming data automatically bypasses risky form data. It is intended to be a security feature that collates incoming data before it is sent to the database, but is not effective because it does not help users prevent common SQL injection attacks. Because most database tiers support prepared statements that better handle this risk, disabling this setting will eliminate this annoying performance issue again.
    • always_populate_raw_post_data-This is only required if you need to view the entire payload of incoming unfiltered data for some reason POST . Otherwise, it stores only one copy of the POST data in memory, which is not necessary.

However, disabling these options on legacy code can be risky because they may depend on their settings for proper execution. You should not develop any new code based on the options that are set, and if possible, you should seek ways to refactor your existing code and avoid using them.

Options for setting should be disabled or adjusted

You can enable some of the excellent performance options for php.ini files to increase your script speed:

    • output_buffering-You should make sure that this option is enabled because it will brush the output back to the browser in blocks, rather than in each echo or every print statement, and the latter will greatly slow down your request response time.
    • variables_order-This instruction controls the Egpcs (,, Environment , Get Post Cookie and Server ) variable parsing order of incoming requests. If you do not use some kind of hyper-global variables (such as environment variables), you can safely delete them to get a little speedup, thus avoiding parsing them on every request.
    • date.timezone-This is an instruction added in PHP V5.1 to set the default time zone and then use it for the function that will be described later DateTime . If you do not set this option in the php.ini file, PHP executes a number of system requests to find out what it is, and in PHP V5.3, a warning is issued for each request.

These are considered "handy" in terms of the settings that should be configured on your production instance. As far as PHP is concerned, there is one more thing to consider. This is the use of your application require() and include() (and its peers require_once() and include_once() ). These functions optimize your PHP configuration and code to prevent unnecessary file status checks on each request, thus reducing response time.

Manage your require() andinclude()

From a performance point of view, a file-state invocation (that is, a call to the underlying file system to check if a file exists) is quite expensive. One of the biggest culprits of file state appears in the require() include() form of statements that are used to bring code into the script. require_once()are include_once() more problematic because they not only need to verify that the file exists, but that it was not previously included.

So what's the best way to solve this problem? You can do something to expedite the resolution.

    • require() include() Use absolute paths for all and calls. This will make PHP clearer about the exact files you want to include, so you don't need to check the entire file for your files include_path .
    • include_paththe number of entries in the hold is low. This is useful in situations where it is difficult to require() provide an absolute path for each and every include() invocation, typically in a large legacy application, by not checking the location of the files that you contain.

APC and Wincache also have mechanisms for caching the results of file status checks carried out by PHP, so there is no need for repeated file system checks. When you leave the include file names static and not variable-driven, they are most effective, so it is useful to try this as much as possible.

Optimize your database

Database optimization will soon become a cutting-edge topic, and I have little room to do this completely impartially here. But if you're looking to optimize the speed of your database, there are a few steps you should take first, which should help with common problems.

Put the database on your own machine

The database query itself can become quite intense, and is typically SELECT limited to 100% of the CPU when simple statements are executed on a reasonably sized set of data. If both your Web server and database server are using CPU time on a single machine, this will undoubtedly slow down your request. So I think the first step is to put the Web server and the database server on separate machines and make sure that your database server is more robust (the database server prefers a lot of memory and multiple CPUs).

Rational design and indexing of tables

The biggest problem with database performance may originate from bad database design and missing indexes. SELECTstatements are typically the most common types of queries that run in a typical Web application. They are also the most time-consuming queries that run on the database server. In addition, these types of SQL statements are most sensitive to proper indexing and database design, so review the instructions below to get tips for achieving optimal performance.

    • Make sure that each table has a primary key. This provides a default order and a quick way for tables to join other tables.
    • Make sure that the index of any foreign key in one table (that is, the key of the record linked to another table) is well-documented. Many databases automatically impose constraints on these keys so that the values really match one record in another table, which helps to get rid of this difficulty.
    • An attempt was made to limit the number of columns in a table. There are too many columns in a table that are longer than the scan time required to query when there are only a few columns. In addition, if you have a table that is not commonly used with more than one column, you are also NULL wasting disk space through the Value field. This is also true for variable-size fields such as text or blobs, where table size growth can be far beyond demand. In this case, you should consider dividing the other columns into different tables and uniting them on the primary key of the record.

Analyze queries running on the server

The best way to improve database performance is to analyze what queries are running on your database server and how long it will take to run them. Almost every database has a tool with this capability. For MySQL, you can use the slow query log to find problematic queries. To use it, set the MySQL configuration file to slow_query_log 1, then set Log_output to file, and record them in Hostname-slow.log. You can set long_query_time thresholds to determine how many seconds a query must run before it is considered a "slow query." I would recommend that you set the threshold to 5 seconds first, and reduce it to 1 seconds over time, depending on your dataset. If you explore the file, you'll see a detailed query similar to Listing 1.


Listing 1. MySQL Slow Query log

/usr/local/mysql/bin/mysqld, Version:5.1.49-log, started with:tcp port:3306 Unix sockets:/tmp/mysql.socktime         Id Command  argument# time:030207 15:03:33# User@host:user[user] @ localhost.localdomain [127.0.0.1]# query_time:13 Lo ck_time:0 rows_sent:117 rows_examined:234use Sugarcrm;select * from accounts inner join leads on accounts.id = Leads.ac count_id;

The key object we want to consider is the Query_time time it takes to display the query. The other thing to consider is the Rows_sent Rows_examined number of amounts, because these can refer to situations where a query is incorrectly written if it looks at too many rows or returns too many rows. You can delve deeper into how to write a query, which is added at the beginning of the query, and EXPLAIN it returns the query plan, not the result set, as shown in Listing 2.


Listing 2. MySQL EXPLAIN Results

Mysql> Explain SELECT * from accounts inner join leads on accounts.id = leads.account_id;+----+-------------+---------- +--------+--------------------------+---------+---| ID | Select_type | Table  | type  | possible_keys       | key   | key_len | ref            | rows | Extra |+----+-------------+----------+--------+--------------------------+---------+--------| 1 | Simple   | leads  | All  | Idx_leads_acct_del    | NULL  | NULL  | NULL           | | |    | 1 | Simple   | accounts | eq_ref | Primary,idx_accnt_id_del | PRIMARY | 108  | sugarcrm.leads.account_id |  1 |    | +----+-------------+----------+--------+--------------------------+---------+---------2 rows in Set (0.00 sec)

The MySQL manual delves deeper into the topic of the EXPLAIN output (see resources ), but one of the important things I consider is ' type ' listed as ' all ' because it requires MySQL to do a full-table scan and does not require a key to execute the query. These help you greatly increase the query speed when you add an index.

Cache data effectively

As we saw in the previous section, databases tend to be a great pain point for the performance of your Web applications. But what if the data you're querying doesn't change very often? In this case, a good choice is to store these results locally instead of invoking the query for each request.

The two opcode buffers we explored earlier APC and Wincache have the tools to do this, where you can store PHP data directly in a shared memory segment for quick querying. Listing 3 provides a concrete example.


Listing 3. Example of using APC to cache database results

     
     Query ($sql) as $row) {      $list [] = $row;    }        Apc_store (' getlistofusers ', $list);  }    return $list;}

We only need to execute the query once. After that, we push the results to the getListOfUsers APC cache under the key. From here, until the cache expires, you can get an array of results directly from the cache and skip the SQL query.

APC and Wincache are not the only choice for a user cache; Memcache and Redis are other popular options that do not require you to run user caches on the same server as the WEB server. This improves performance and flexibility, especially when your Web application is scaled out across multiple Web servers.

In this article, we explored 5 simple ways to tune your LAMP performance. Not only did we explore PHP-level technology by leveraging an opcode cache and optimizing PHP configuration, but we explored how to optimize your database design to achieve proper indexing. We also explored how to use a user cache (APC as an example) to demonstrate how to avoid duplicate database calls when the data does not change frequently.

http://www.bkjia.com/PHPjc/323773.html www.bkjia.com true http://www.bkjia.com/PHPjc/323773.html techarticle Introduction to the main web properties such as Wikipedia, Facebook and Yahoo! Use the LAMP architecture to service millions of of requests per day, and Web applications such as Wordpress, Joomla, Drupal, and SugarCRM ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.