banner code cached
Tips and tricks

Limiting the consumption of server resources

articles

Limiting the consumption of server resources

Author: Daniel | added: January 14, 2020

As our website grows, we will start to notice significant drops in performance. One of the main causes of novice programmers is poor server resource management. Many people are afraid of using the cache memory, and this is quite a serious mistake.

1. Purpose of the script

Let's assume that we are creating a website for a game created on Unity. We wrote the page, styled it, and put a game on it that was provided by another developer. After a while, you come up with the idea of a scoreboard stored in a database. The game programmer extracts the points data and provides them to you. You process this data and save it in the database. Additionally, on the website you place an array that retrieves this data from the database. What will happen?

At best, the page under load will stop loading for subsequent users. This is because each new user entering the website runs a script that downloads data from the database, which loads the server. Fortunately, this can be remedied in a banal way.

We will use the next two scripts in two separate files for this. They will be needed to save the result of the previously mentioned script result. And more specifically?

  1. After launching the website, the first user enters it
  2. The basic script contained in the file .php executes normally, and our next two scripts remember its result in a file .html
  3. The next user entering the website now will no longer load the same script again, but will download our new file much faster .html
  4. After the time set by us, our file .html will die and be generated again - this is to refresh the data

2. Pros and cons

This solution, although it will speed up the loading of the page for many users. It has several significant drawbacks. Note that after each process of saving the output of the .php as a file .html, data downloaded, for example, from a database will not be refreshed on an ongoing basis for each user. For the lifetime of one file .html the results in the sample game scoreboard will be from the moment this file is generated, until the next generation.

It also cannot be used for every file. You have to find out for yourself whether in the case of our website something needs to be updated on a regular basis for each unique user.

However, this seems to be a minor drawback if we can limit references to the database from 200 to 1 with e.g. 200 simultaneous users.

3. Implementation

To implement this method, we will need min. 3 files .php:

  1. File with the script placed at the top of the target file - it will be responsible for checking whether the generated file already exists .html and whether it is already too old.
  2. The file with the script placed at the bottom of the target file - it will be responsible for the end of the file generation .html, saving it to the cache and sending information to the browser.
  3. Target file - any page containing a PHP script that we want to optimize.

3a. Top-cache.php

$url = $_SERVER ["SCRIPT_NAME"];
$break = Explode ('/', $url);
$file = $break [count ($break) - 1];
$cachefile = 'cached -'. Substr_replace ($file, "", - 4). '. Html';
$cachetime = 600; // Here we set the cache lifetime in seconds - currently it is 10 minutes
// Serve from the cache if it is younger than $cachetime
if (file_exists ($cachefile) && time () - $cachetime <filemtime ($cachefile)) {
    echo " \ n ";
    readfile ($cachefile);
    exit;
}
ob_start ();
?>

3b. Bottom-cache.php

$cached = fopen ($cachefile, 'in');
fwrite ($cached, ob_get_contents ());
fclose ($cached);
ob_end_flush ();
?>

3c. Index.php

    include ('php / top-cache.php');
    $db = mysqli_connect (...);
    $get_scores = 'SELECT * FROM score_board ORDER BY Result DESC LIMIT 10';
    $scores = mysqli_query ($db, $get_scores);
?>
    
    
    
        
             TOP 10
        
    
    
        
            
                
                    Modal title
                    
                        ×
                    
                
                
                    
                        

SCOREBOARD
(results are refreshed every 10 minutes)

                        
                            
                                
                                
                            
                            
                                foreach ($scores as $user) {
                                    echo ‚
';
                                }
                            ?>
                        
NameScore
'.$user [' Name '].' '.$user [' Result '].' point
                    
                
                
                    CLOSE
                
            
        
    
    include ('php / bottom-cache.php');
?>

Using the function include () at the beginning of the file index.html (or any file we want to optimize) attach the file top-chache.php. It will check if the result file is already generated and if it is not too old to show to the user. In the event that such a file does not exist or is too old, the server will generate it for the first user who enters the page (it will take a little longer than the next page loads, because the php scripts contained in it must be executed) and saves it on the server. Each subsequent person who enters the website will see the generated file. It is important to use this solution wisely and not to save data in this way, which should be different for each user.

Leave a Reply

Your email address will not be published. Required fields are marked *

en_USEnglish