The topic of this article is the fact that using FastCGI in PHP does not speed up the loading time of PHP code compared to, for example, mod_php.

Most traditional Web programming languages ​​(Perl, Ruby, Python, etc.) support writing scripts that work in the so-called “FastCGI mode”. Moreover, Ruby on Rails, for example, cannot be used at all in CGI mode, because it spends tens of seconds connecting all its numerous libraries.

Below I will talk about a method that allows, in some cases, to speed up the loading of voluminous PHP code by more than 20 times, without side effects or significant inconvenience. But first, let's talk about the basics...

What is FastCGI?

First, let's talk about what is called the “classic” FastCGI, which is used in C, Perl, Ruby, etc. In PHP, FastCGI has its own characteristics, we will look at them a little later. Now we are talking about non-PHP.

FastCGI works like this: the script is loaded into memory, runs some heavy initialization code (for example, including large libraries), and then enters a loop processing incoming HTTP requests. The same script process processes several various requests one after another, which differs from working in CGI mode, when a separate process is created for each request, “dying” after processing is completed. Usually, after processing N requests, the FastCGI script ends so that the server restarts it again in a “clean sandbox”.

To speed up processing, of course, not one script process starts, but several at once, so that each subsequent request does not wait for the previous one to be processed. Both the number of simultaneously launched processes and the number of sequential requests per process can be set in the server configuration.

Old scripts written with CGI in mind need to be modified so that they can work in a FastCGI environment (applies to using FastCGI in C, Perl, etc.; no modification is needed in PHP, but this has its drawbacks, see below) . Indeed, before, the script started each time “from scratch,” but now it has to deal with the “garbage” that was left over from the previous request. If previously a CGI script in Perl looked like

useSomeHeavyLibrary; print "Hello, world!\n";

then after modification for FastCGI it becomes like something like

useSomeHeavyLibrary; while ($request = get_fastcgi_request()) ( print "Hello, world!\n"; )

This results in savings in response speed: after all, every time a request arrives, the script does not need to execute “heavy” library initialization code (sometimes taking tens of seconds).

FastCGI has a significant drawback: a new request begins to be processed not in a “clean” environment, but in the one that remains “from last time”. If a script has memory leaks, they gradually accumulate until it crashes. The same applies to resources that they forgot to release ( open files, database connections, etc.). There is one more drawback: if the script code has changed, you have to somehow inform the FastCGI server about this so that it “kills” all its processes and starts again.

Actually, the “initiate once, process many requests” technique works not only in FastCGI. Any server written in the same language as the script running under it uses it implicitly. For example, the Mongrel server is written entirely in Ruby precisely in order to quickly run Ruby On Rails under it. The Apache Tomcat server, written in Java, quickly executes Java servlets because... does not require their reinitialization. mod_perl technology is also based on the fact that Perl code is not unloaded between requests, but remains in memory. Of course, all of these servers have the same problems with unpredictability, memory leaks, and difficulty restarting as the FastCGI application.

Why FastCGI doesn't speed up PHP

You've probably heard that PHP can also be run in FastCGI mode, and that many high-load projects do this (Mamba, some Mail.Ru projects, etc.). This supposedly gives a "significant boost" in performance because (according to rumors) FastCGI saves time on script initialization and library inclusion.

Don't believe it! In reality, PHP's FastCGI support is purely nominal. More precisely, it does not provide advantages in the sense in which it is used to be used to reduce script initialization time. Of course, you can run a PHP FastCGI server and even have nginx or lighttpd work with it directly, but the speedup you get from loading code will be zero. Heavy PHP libraries (for example, Zend Framework) took a long time to load in mod_php or CGI modes, and will continue to load for a long time in FastCGI mode.

Actually, this is not surprising: after all, in order to run any PHP script in FastCGI mode, you do not have to modify it. Not a single line of changed code! When I first decided to experiment with FastCGI in PHP, I spent several hours searching the Internet for information on exactly how to modify PHP code to optimally run it in FastCGI mode. I studied all the PHP documentation and several dozen PHP developer forums, even looked source PHP, but haven't found a single recommendation. Having previous experience with FastCGI in Perl and C, I was incredibly surprised. However, everything fell into place when it turned out that there was no need to change the code and, although several connections are processed within one FastCGI process, the PHP interpreter is initialized anew each time (unlike the “classic” FastCGI). Moreover, it seems that most PHP developers who happily use FastCGI+PHP are not even aware that it should work any differently...

eAccelerator: Accelerating PHP Code Reloading

Every time a PHP script receives control, PHP compiles (more precisely, translates) the script code into an internal representation (bytecode). If the file is small, the translation occurs very quickly (Zend Engine in PHP is one of the leaders in translation speed), however, if the included libraries “weigh” several megabytes, the translation is delayed.

There are a number of tools that cache in shared space. random access memory(shared memory) translated internal representation of PHP code. Thus, when the PHP file is re-enabled, it is no longer translated, and the bytecode is taken from the cache in memory. Naturally, this significantly speeds up the work.

One such tool is eAccelerator. It is installed as PHP extensions(connected in php.ini) and requires minimal configuration. I recommend enabling the bytecode caching mode exclusively in RAM and disabling compression (set the parameters eaccelerator.shm_only=1 and eaccelerator.compress=0). Also install and configure the control.php control panel that comes with the eAccelerator distribution to monitor the cache status in real time. Without control panel It will be very difficult for you to carry out diagnostics if the eAccelerator does not work for some reason.

The advantage of eAccelerator is that it works very stable and fast even on large volumes of PHP code. I've never had any problems with this tool (unlike Zend Accelerator, for example).

“My script together with libraries takes up 5 MB, what should I do?..”

Do you think 5 MB of code is too much for PHP? Nothing like this. Try systems like Zend Framework and Propel to see otherwise. The entire Zend Framework takes up about 5 MB. The classes generated by Propel are also quite large and can take up several more megabytes.

Many people will laugh at this point and say that there is no need to use Zend Framework and Propel, because... they are slow. But the reality is that they are not even slow at all... The method that by default uses PHP to load code has poor performance. Fortunately, the situation is not difficult to correct.

In order not to be unfounded, I will present the results of a small test that I specifically conducted in a “clean” environment, not tied to any specific project. The connection speed of all Zend Framework files (with the exception of Zend_Search_Lucene) was tested. All require_once calls were previously removed from the code, and dependencies were loaded only through the autoload mechanism.

So, in total, 790 PHP files were connected with a total volume of 4.9 MB. Quite a lot, right? The connection went something like this:

function __autoload($className) ( $fname = str_replace("_", "/", $className) . ".php"; $result = require_once($fname); return $result; ) // Connect the classes one by one in order of their dependencies. class_exists("Zend_Acl_Assert_Interface"); class_exists("Zend_Acl_Exception"); class_exists("Zend_Acl_Resource_Interface"); class_exists("Zend_Acl_Resource"); // ... and so on for all 790 files

Because autoload is used, calling class_exists() forces PHP to include the appropriate class file. (This is the easiest way to “pull” the autoload function.) I chose the connection order in such a way that each subsequent class already had all its dependent classes loaded at the time of launch. (This order is easy to establish by simply printing the value of $fname in the __autoload function to the browser.)

Here are the test results with and without eAccelerator on mine, not very good powerful laptop(Apache, mod_php):

  • Connecting all files one at a time, eAccelerator disabled: 911 ms.
  • Connecting all files one by one, eAccelerator enabled: 435 ms. 15 M of cache memory is occupied for bytecode.

As you can see, eAccelerator gives approximately 2x speedup on 790 files with a total volume of 4.9 MB. A bit weak. In addition, 435 ms is clearly too much for a script that does nothing but include libraries.

Now let's add some steroids

Rumor has it that PHP loads one large file much faster than ten small ones of the same total size. I decided to test this claim by combining the entire Zend Framework into one 4.9 MB file and connecting it with a single require_once call. Let's see what happened.

  • Enabling one large merged file, eAccelerator disabled: 458 ms.
  • Enabling one large merged file, eAccelerator enabled: 42 ms. 31 MB of bytecode cache is occupied.

The first line says that one large file of 4.9 MB in size actually loads faster than 790 small ones: 458 ms versus 911 ms (see above). 2x savings.

But the second line made me jump in my chair in surprise and double-check the result several times. I hope the same happens to you. Indeed, 42 ms is 11 times faster than with eAccelerator disabled! It turns out that eAccelerator loves small files even less (by the way, even in eaccelerator.check_mtime=0 mode): 11-fold savings.

So, we actually got 22x faster loading times, just as promised in the title. Previously, the entire Zend Framework, divided into files, took 911 ms to connect, and using eAccelerator and combining all the files into one - 42 ms. And this, mind you, is not on a real server, but just on an ordinary laptop.

Conclusion: 22 times faster

Let's summarize.

  • Merge all files into one big one plus enable eAccelerator for this large file gives a 22x speedup with a code size of 4.9 MB and the number of files 790.
  • For a small number of large files, eAccelerator can provide 10x speedup. If there are a lot of files and the total volume is large, then the speedup is approximately 2 times.
  • Cache memory consumption depends on the number of partition files: for a fixed size, the more files there are, the less consumption.

With all this, eAccelerator does not have the main problems of a “real” FastCGI server. Scripts are free of memory leaks and run in a guaranteed “clean” environment. You also do not need to monitor code changes and restart the server every time modifications are made to the more or less deep code of the system.

Note also that we included the entire Zend Framework. In real scripts, the amount of code will be much less, because Typically only a small portion of ZF is required for operation. But even if the libraries occupy 4.9 MB, we get a loading time of 42 ms - quite acceptable for a PHP script. After all, in busy projects, PHP scripts can work for several hundred milliseconds (Facebook, My Circle, etc.).

Of course, if you plan to run FastCGI in PHP not for performance reasons, but simply to avoid being tied to Apache and limit yourself to the “nginx+PHP” or “lighttpd+PHP” combination, nothing prevents this. Moreover, by using eAccelerator for FastCGI+PHP and merging many code files into one large one, you will get the same acceleration that I described above. However, do not flatter yourself with hopes that it was FastCGI that gave the acceleration: this is not so. Using mod_php+eAccelerator, you would achieve almost the same result as FastCGI+eAccelerator.

Manually merging all library files into one is a tedious task. It is better to write a utility that will automatically analyze the list of PHP files included by the script, and the next time it is launched, combine these files and write them to a temporary directory (if this has not already been done), and then connect them using require_once. Today I leave the writing of such a utility (give or take details) to the reader’s conscience.

I also recommend that you abandon the explicit inclusion of files using require_once and switch to autoload. Just don’t try to use Zend_Loader for this: it is very slow (according to my measurements, connecting a hundred files will take about 50 ms extra). It’s better to write your own simple autoload function that will quickly do all the work. Autoload will allow you to safely combine multiple library files into one without having to worry about how to deal with manual require_onces.

Finally, use the set_include_path() function so that the library inclusion code looks like this:

require_once "Some/Library.php";

require_once LIB_DIR . "/Some/Library.php";

Constants that explicitly define the path to the library directory are a big evil and complicate the program. They also indirectly contradict the Zend Framework and PEAR coding standards, which I also recommend adhering to whenever possible.

So, if you want to use “heavy” libraries in PHP scripts, good luck! PHP is a scripting language that truly allows you to do this without regard to the inconveniences of FastCGI and the problems of “built-in” servers.

When developing large projects, the question of optimizing the project code gradually arises: how justified is the memory consumption, how can you increase the execution speed of the written PHP code. At first, many people do not think about the correctness and efficiency of the written code; they write according to the principle: it works - and that’s okay. Although the PHP interpreter is quite fast at executing PHP code, and there are many bottlenecks that slow down code execution that are outside of PHP, PHP code optimization is also important, and code optimization should be applied early in the coding process .

Most PHP scripts do simple steps. The standard behavior of the script is to download a small amount of information from the user, retrieve some information from a database or file, output the appropriate HTML, and send the result to the client. Here, the first thing you need to understand is what exactly should be the result of optimization: performance, ease of scaling, reducing the amount of server resources used, reducing data transfer time, or all together. In the latter case, it is necessary not only to find all critical areas, but also to balance their optimization.

Let me give you a simple example: let there be two scripts on a server with 100 MB of free RAM, the result of which is the same. The first script is optimized for maximum performance, requires 10 MB of memory and receives data from a file by reading it completely, the second is optimized for minimal memory consumption, requires 5 MB of memory and receives data from the same file in parts. As a result of one request, the first script will be executed faster than the second, but if there are more than ten requests at the same time, it is the speed of the second script that will become higher. Why is this happening? In the first script, the bottleneck is the use of memory resources, in the second - the features of the I/O system. After the first script consumes all available RAM, the system will switch to using virtual memory, and the same I/O system will become an additional bottleneck of this scheme.

Of course, this example is greatly simplified, and there are other bottlenecks besides RAM, but the main idea is this: optimization for one case can become a critical point in another. In the example, as a result of optimization for a slight increase in speed at low loads, the speed of script execution at higher loads significantly decreased. Therefore, to get better returns, it is important to spend your energy optimizing the areas that truly deserve attention.

I will not consider here optimizing the operating system, optimizing server settings, etc., because... Most webmasters use hosting and, accordingly, will not be able to set everything up on their own. Only PHP code optimization will be considered here. It should be noted that in each specific case, some types of optimization will be useful, others will be a waste of time and effort. Often the benefit of improving the code will be negligible. Perhaps, over time, internal changes in PHP will render successful optimization useless or even harmful.

Below are the main performance steps for PHP 5 version:

Actions to optimize RAM consumption:

  1. Analyze the results of your functions. Before writing a function, check to see if there is a standard equivalent.
  2. Freeing memory when large arrays or objects are finished being used only in the global scope (memory will be freed automatically in the local scope). Please note that the function unset() removes a variable from the scope and, only if there are no other references to the object, frees the memory occupied by the object. Assignment value variable null always destroys the object and frees the memory occupied by the object, regardless of whether there are still references to this object. In this case, the variable will not be removed from the scope, i.e. in fact, the variable will contain an undefined (zero) value and, accordingly, will occupy memory for the contents of this variable (about 72 bytes).
  3. Analysis of the justification for using OOP (object-oriented programming). Before writing object-oriented code, ask yourself two questions: “Does this require an object-oriented approach?” and “can I write object-oriented code?” For example, defining a static function inside a class increases the amount of memory required just to contain that function by 10-18%. Using an array rather than a class as the structure also saves memory. It may be more profitable to simply put the functions in a separate file, rather than implement them as class methods.
  4. Analysis of the possibility of implementing a static version of a method in a class. If the method does not use a parameter $this, then it must be declared using the keyword static.

Actions to increase code execution speed:

  1. Analysis of SQL query optimization. In most projects, it is the optimization of SQL queries that gives greatest increase productivity.
  2. Using output buffering and various caching modules can increase performance by 25% -100%.
  3. Using shorter short names for variables, functions, constants, and classes can improve performance by up to 20%. At the same time, do not forget about further code support, telling name functions are much more convenient when modifying code.
  4. Checking the existence of a variable (function isset()) before contacting her. Suppressing the error that occurs when accessing a non-existent variable by using @ is a huge performance hit.
  5. Using "single quotes" allows you to interpret the code faster, because in the case of “double quotes”, variables are searched inside the string
  6. Analysis of the possibility of removing “extra” functions from the loop. For example, replacing a function count() to a variable calculated before the start of the loop and containing the result of this function, in the expression for($i=0; $i will increase the productivity of this cycle. Otherwise the function count() will be called and executed on every iteration of the loop.
  7. Using the operator case instead of using multiple constructs if...else.
  8. Using explicit access to array fields. Reversal of the form $array["id"] runs 7 times faster than reversal $array. In addition, this protects against errors during further support of the script, because one day there might be a constant named id.
  9. Using an additional variable containing a reference to the final array when processing multidimensional arrays in a loop. To speed up the cycle for($i = 0; $i< 5; $i++) $a["b"]["c"][$i] = func($i); , before the start of the loop it is possible to write the next instruction $item =p$a["b"]["c"] and rewrite the loop like this: for($i = 0; $i< 5; $i++) $ref[$i] = $i; .
  10. Using the Apache mod_gzip and mod_deflate modules allows you to reduce traffic, thereby increasing page loading speed.

The following code optimization steps improve performance only when used repeatedly:

  1. Usage +$i instead of $i++ in cycles gives a performance increase of 6%.
  2. Using "double quotes" to concatenate variables. Instruction of the form $s="$s1$s2$s3" interpreted faster than $s=$s1.$s2.$s3. This statement is only true for three or more variables.
  3. Using full paths in instructions include And require will allow you to spend less time searching for the system to find the real path.
  4. Closing open connections to the database after they are no longer needed. At the same time, you should not connect to the same database multiple times.
  5. Replacement feasibility analysis include() And include_once() on require() And require_once() respectively.
  6. Using HTML inserts into the code, instead of outputting a significant amount of static lines (not containing the results of the code). In general, the speed of issuing a static page (HTML) is several times faster than issuing a page written in PHP. But you shouldn’t get carried away here, because... Entering and exiting the interpreter into PHP processing mode also loads the server.
  7. Analysis of the possibility of replacing functions preg_replace And str_replace in some cases. Function str_replace works faster than preg_replace, and at the same time the function strtr faster functions str_replace. Also, using string functions strncasecmp, strpbrk And stripos more optimal than using regular expressions. However, instead of nesting these functions, you should use regular expression functions.
  8. Using explicit variable initialization. For example, the increment of an uninitialized variable is 9-10 times slower than a previously initialized one. In addition, there are fewer errors when initializing variables explicitly.
  9. As a conclusion, I would like to note that the use of the design echo, instead of a function print, does not provide a noticeable increase in productivity.
  • To determine the start time of script execution, instead of functions that return the current time, it is preferable to use $_SERVER["REQUEST_TIME"].
  • Use a profiler to identify critical sections of code.

Before optimizing code performance, I strongly recommend checking the optimization of SQL queries to the database, as well as optimizing http queries, reducing the size of js and css, thinking about caching templates, and only after that start testing the code for performance.

Good programming style involves optimizing while writing code, rather than patching holes later.

Good day to all.

  1. If a method can be static, declare it static.
  2. echo is faster than print.
  3. Pass multiple parameters to echo instead of using string concatenation.
  4. Set the maximum number of times your for loops can pass before the loop, not while it's executing.
  5. Delete your variables to free up memory, especially if they are large arrays.
  6. Beware of magic methods like __set, __get, __autoload.
  7. require_once comes at a cost.
  8. Specify full paths in include/require constructs, less time will be spent searching for the file.
  9. If you need to determine the time the script was run, use $_SERVER['REQUEST_TIME'] instead of time().
  10. Try to use strncasecmp, strpbrk and stripos instead of regular expressions.
  11. str_replace is faster than preg_replace, but strtr is faster than str_replace.
  12. If the function, like string replacement functions, can take both arrays and single characters as arguments, and if your argument list is not too long, consider writing multiple identical replacement expressions, going through one character at a time, instead of one string code that takes an array as a search and replace argument
  13. It is better to select statements using else if statements rather than using multiple if statements.
  14. Error suppression when using @ is very slow.
  15. Use the Apache mod_deflate module.
  16. Close your database connections when you are done working with them.
  17. $row["id"] is seven times faster than $row.
  18. Error messages are expensive
  19. Don't use functions inside a for loop condition, like this: for ($x=0; $x< count($array); $x). В данном случае функция count() будет вызываться с каждым проходом цикла.
  20. Incrementing a local variable in a method is the fastest. Incrementing a local variable in a function works almost the same way.
  21. The increment of a global variable is twice as slow as that of a local one.
  22. Incrementing an object property (ie $this->prop++) is three times slower than a local variable.
  23. The increment of an undefined variable is 9-10 times slower than that of a pre-initialized one.
  24. Declaring a global variable without using it in a function also slows down the work (by about the same amount as incrementing a local variable). PHP is probably checking to see if the variable exists.
  25. The speed of method invocation does not seem to depend on the number of methods defined in the class. I added 10 methods to the test class (before and after the test method), with no performance change.
  26. Methods in derived classes work faster than those defined in the base class.
  27. Calling a function with one parameter and an empty function body on average equals 7-8 increments of the local variable ($localvar++). Calling a similar method, of course, takes about 15 increments.
  28. Your strings defined with " rather than " will be interpreted a little faster because PHP looks for variables inside "..", but not "...". Of course, you can only use this when there are no variables in your string.
  29. Comma-separated lines are printed faster than dot-separated lines. Note: This only works with the echo function, which can take multiple lines as arguments.
  30. PHP scripts will be processed at least 2-10 times slower than static HTML pages. Try using more static HTML pages and fewer scripts.
  31. Your PHP scripts are recompiled every time if the scripts are not cached. Script caching typically improves performance by 25-100% by removing compilation time.
  32. Cache as much as possible. Use memcached, a high-performance in-memory object caching system that improves the speed of dynamic web applications by making database loading easier. Cached microcode is useful because it prevents your script from having to be compiled again for every request.
  33. When working with strings, when you need to ensure that a string is a certain length, you will of course want to use the strlen() function. This function works very quickly, because it does not perform any calculations, but only returns the already known length of the string available in the zval structure ( internal structure C, used when working with variables in PHP). However, because strlen() is a function, it will be slow due to the fact that it will call some operations, such as lowercase string conversion and hash table lookups, before the function's main actions are performed. In some cases, you can speed up your code by using the isset() trick.
    Was: if (strlen($foo)< 5) { echo «Foo is too short»; }
    Now: if (!isset($foo(5))) ( echo “Foo is too short”; )
    Calling isset() is faster than strlen() because, unlike strlen(), isset() is not a function, but a language construct. Due to this, isset() has virtually no overhead for determining the length of the string.
  34. Incrementing or decrementing a variable using $i++ is slightly slower than ++$i. This is a special feature of PHP, and you shouldn't modify your C and Java code in this way thinking that it will run faster, it won't. ++$i will be faster in PHP because instead of four commands as with $i++, you only need three. Post-incrementation is typically used when creating temporary variables that are then incremented. While the pre-increment increases the value of the original variable. This is one of the ways to optimize PHP code into bytecode using the Zend Optimizer utility. However, this good idea, since not all bytecode optimizers optimize for this, there are also many scripts that work without bytecode optimization.
  35. Not everything needs to be OOP; this is often unnecessary since each method and object takes up a lot of memory.
  36. Don't define every data structure as a class, arrays can be very useful
  37. Don't break down the methods too much. Think about what you will actually reuse.
  38. You can always break the code into methods later, as needed.
  39. Use countless predefined functions.
  40. If your code has functions that take a very long time to execute, consider writing them in C as an extension
  41. Profile your code. Profiling will show you how long parts of your code take to execute.
  42. mod_gzip is an Apache module that allows you to compress your data on the fly and can reduce the amount of data transferred by up to 80%.

From the author: Every self-respecting developer worries about the “fate” of his code. Tries to make the application as convenient, faster and increase its fault tolerance as possible. But PHP optimization will not always allow you to reach these heights.

Don't heal your arm if your leg is lame!

Sorry for the Irish folk aphorism! But it perfectly reflects the essence of the problem. Most often, code optimization will not allow you to improve the performance of the created script or resource. And in the case of , everything becomes extremely complicated due to a large number of factors that you (as a developer) simply cannot influence.

As for phenomena beyond our control, I mean the speed of the Internet connection, server load, OS settings on the client machine, and the power of the user’s PC hardware. You will not be able to influence all these components. And in the end it turns out that the optimization of the PHP code will not give a full result.

What remains under the control of a web developer:

Server settings are limited. Setting parameters through the Apache httpd.conf configuration file allows you to set the number of child processes, socket connection timeout, output buffer size for TCP/IP connections, idle time, and others.

Language core settings - through the parameters specified in the php.ini file. Allows you to set buffering values, change the maximum script execution time, error handling, log management and other settings.

WITH using PHP image optimization - more on that later. Optimization of program code - allows you to “save” resources and increase performance.

For example, you need to know that echo is faster than print. It is better to turn off error messages after debugging to save resources. Instead of string concatenation, use echo. Class objects and methods () eat up a lot of memory.

Working with Images

I'm not a fan of server-side image processing. This also leads to a waste of precious resources, of which hosting is always in short supply. It turns out that by saving on one thing, we waste other “reserves”.

A more optimal option is to upload images to a third-party service, from where they are loaded in an optimized form into the user’s browser at a given address. There are many such services on the Internet. I want to name just a few of them: kraken.io, TinyPNG

As you can see, knowledge search engine optimization in PHP is also important for professional developers.

In addition, it has its own built-in tools for “lightening” images. For example, the imagecopyresampled() function. It reduces the weight of content by resampling and resizing the image. Usage example:

header("Content-Type: image/jpeg");

$file = "sample.jpg" ;

$img_obrabot = imagecreatetruecolor(200, 100);

$img_orig = imagecreatefromjpeg($file);

imagecopyresampled($img_obrabot, $img_orig, 0, 0, 0, 0, 200, 100, 541, 286);

imagejpeg ($img_obrabot) ;

What else can you do?

Also don't forget to apply client side optimization using PHP. To some extent, the server can influence the client browser through Cache-Control, as well as the attributes of this header: post-check, max-age and others.

In addition, the Last-Modified and ETag headers allow you to manage the state of the cache on the client machine. They set a unique ID to modify each file. Thanks to this, the server does not resend resources, but only replies with a 304 status.

In the article we did not raise the issue of optimization using PHP FPM. But to consider it will require a separate article. That's all for today. Until next time!


How to force without much effort PHP-code works fine faster? Before asking questions about caching and scaling, you should try to optimize the code. There are a number of simple rules:

More about optimization...

When inserting pieces of PHP code into HTML pages, always use full opening and closing parentheses! This will protect you from variations in php.ini short_open_tag settings on different servers and possibly save a lot of time when transferring or uploading projects to different servers.

Try to use the echo output function instead of printf and sprintf whenever possible. There is no need to use these functions, since they are slower because they are designed to interpret and output a string with its processing, value substitution, in formatted form. This is what the letter f at the end of the names of these 2 functions indicates.

Sprintf("mother"); printf("dad");

Echo "mother"; echo "dad";

For the same reasons, use single quotes whenever possible and use the "." operator. to concatenate strings, instead of directly substituting a variable into a string enclosed in quotes.

Best option (fastest)

Echo "The weight is: ".$weight;

Worst case (slow):

Echo "Weight is: $weight";

If you need to check whether the returned value of a function is equal to zero (and the function itself returns only positive or only negative values), then it is better to use the comparison operator. It is faster than a specific comparison of values.

$i = 0; if ($i != 0) ( //Not equal) else ( //Equal)

$i = 0; if ($i > 0) ( //Not equal to ) else ( //Equal to ) It should also be taken into account that if a string accepts only empty values, or user string data, then instead of comparing string with string to identify its emptiness, also You can use comparison with zero, which will be faster.

To check if a string is empty, use the function trim($str) ; It will not only check whether the string is full, but will also trim off unimportant characters - spaces (tabs, white-spaces) and return a positive value if there are indeed some significant characters in the string.

If ($str != "") ( //string processing)

If (trim($str)) ( //string processing)

To obtain data from forms using the Get and Post method, it is better to use the following minimum set self-written functions:

GetParam ($array, $value, $default = "") ( return (isset($array[$value])) ? $array[$value] : $default; ) GetParamSafe ($array, $value, $default = "") ( return (isset($array[$value])) ? addslashes($array[$value]) : $default; )

The GetParam($_POST, "myvar", "empty") function, for example, will correctly receive data from $_POST["myvar"], and if the $_POST variable does not exist, it will return the default value, without any Waring and Notice. The GetParamSafe($_POST, "myvar", "empty") function does the same operation, but returns an escaped variable. For protection against SQL injections, for example. A this design allows you to get integer from $_POST.

Intval(GetParam($_POST, "myvar", "empty")):

If the $_POST array did not contain a number at all, the function will return 0;

For simple string comparisons, do not use preg_match() or preg_match_all() . Use strstr() and strpos() .

When fetching rows from a database (MySQL for example), try to use the mysql_fetch_object function. For example, when changing the request code from

$query = "SELECT field7, field3 FROM mytable WHERE id = 5" to $query = "SELECT * FROM mytable WHERE id = 5" code for outputting the row obtained from these queries $row = mysql_fetch_array(mysql_query($query)); echo $row."-->".$row; //stops working while $row = mysql_fetch_object(mysql_query($query)); echo $row->field7."-->".$row->field3; // will remain operational.

When using sessions for authorization on the site, store in the session at least the IP address from which you logged in. Also check the input IP with the current IP address every time you execute a closed script. For example, if an attacker manages to steal the session name, he will no longer be able to enter the closed part. Because in general it will have a different IP address.

When creating large queries for inserting data into the database using insert, try to place all lines in one or three inserts. Executing each line separately will not only load the database server, but will also delay the work of your script.

If you need to use the same difficult-to-calculate data in different places (different classes) of the same system (for example, which is obtained from the database through a query with subsequent row processing), try to calculate it once, store it globally for the entire system and transfer it to the class( script) once, directly when creating a class (connecting a script)

If your Web server is under heavy load, consider using standard solutions to enable cache (cache technology). For example, the free PHP class JCache_Lite_Function.

When designing/developing large systems, give preference to Object-Oriented Programming using design patterns. Most common patterns: MVC, PageController, BodyHandler, Fabric...


Read more: