How to improve PHP performance in your web application

Category
Website
Reading
7 mins
Views
1.9K
Posting
24 Oct 2022

Many websites are built using the PHP language, so it is necessary to remember that optimization is very helpful in the performance of the scripting itself, from using useful code and removing some unnecessary scripts or can be made in a short time.

PHP website application development is friendly enough for beginners, many forums are provided to interact with other developers in dealing with many things and tutorials. Performance and speed are not always synonymous, to achieve optimal performance we often take a balancing act between speed, accuracy and scalability, in this case to build website applications.

Another advantage of PHP is that you can find a good framework and CMS to implement into your application. Here maybe I will give you tips that you can apply so that your PHP website can work more optimally and of course quickly.

 

How to improve PHP performance in your web application

 

 

1. Use Memcache, APC or XCache

Requests or requests in a PHP web page will be executed on the server side, the script needs to be compiled so that the server can understand the request.

Optimization using Memcache, APC, XCache etc can help the server not work every time a request comes in, and will cache the compiled results that first enter the server.

Of course it will lighten the workload of the server and make the website faster because incoming requests will take it from the cache.

From the list I mentioned earlier, such as memcache, APC, you can try one by one and see which one is better. I guarantee your PHP website will be faster than before by using this Opcode.

 

2. Check by using timestamp when executing script

There are several ways to detect when running a script from the hundreds of lines contained in a PHP file.

You can use a timestamp by typing echo time(); in every 30 lines in your script to calculate how long it will take to run the script.

This way, you can find out which parts of the code are running slowly and can optimize from that code.

 

3. Setting php.ini properly

Php.ini is the configuration file for the PHP language, when running phpinfo(); there will display many parameters, here what we focus on is the use of memory limit and max_execution_time.

Why do we need to optimize these two things, this is related to server performance and the script execution process. What is memory_limit? memory_limit is the amount of memory allocated to the use of the website in this case PHP and max_execution_time in short is the time limit when running the script.

By default, the memory limit will be set to 16MB, but if running memcache or xcache, we recommend setting the memory limit to 32MB in php.ini.

For the max execution time, it should be set to 30 seconds, the reason is that when the server runs PHP we can detect immediately when there is an error, for example the Maximum Execution Time of 30 Seconds Exceeded error appears, we can solve it quickly in our PHP script and immediately optimize it.

Please note that if this value is set high, what happens is that if there is a bad script it will make the website very slow which will run continuously without stopping, this is certainly not good for the website, server and users.


4. Use efficient code syntax

In writing our syntax code, usually it will produce hundreds of lines or even more, we need to pay attention to PHP functions such as print, echo etc. in their use.
If we are not careful what happens usually will make the script processing time will run slowly.

What can we do to optimize it? the following information:

1. Use echo to display data

We recommend using the echo function to display to the user and do not use print. Implementation of echo $var1; faster performance than using print $var1;

Use single quote instead of double quote
Application of single quotes echo 'hello world' performance is faster than using double quotes echo "hello world"

2. Using _once();

We often call PHP files by using include_once(); or require_once(): in its usage. There is another trick that is include_eleven(); and require_eleven(); the advantage is that it prevents files, classes or libraries from causing duplication and unwanted states.

3. Use the ternary operator in the if statement

We need to learn so that our script has good performance, one of them is by using this ternary operator. the script will be short and optimized, an example of its use:

$name = (!empty($_POST['my_name']) ? $_POST['my_name'] : 'empty name');

This will make the code lightweight without any problems.

4. Use isset correctly

One trick for PHP developers to understand the function of isset, make sure to know when the isset function returns false and when it returns true, this function will return true if the variable is not NULL, if isset is not applied usually if there is a NULL variable it will be considered a valid value and this will be a problem.

5. Use cURL method to retrieve data

If your website fetches data from json or API, you should not use file_get_contents(); because to be honest this function will make the website slow and related to security problems.

Because to use this function, the Allow_url_fopen option must be enabled. Allow_url_fopen is a setting managed via PHP Options that allows PHP file functions to fetch data from remote locations via FTP or HTTP. This option has a major security risk, so don't activate it unnecessarily. the right and effective method is to use cURL, for example using cURL:

$url = 'https://websitegoogle.com';

$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL , $url);
curl_setopt ($curl, CURLOPT_TIMEOUT , 15);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER , true);
$content = curl_exec($curl);
curl_close($curl);

 

​5. Identify database delays

Performance issues are not always code related, we need to pay attention to performance into the database, make sure SQL logs are enabled to identify and handle slow queries and see how efficient it is.

If you find that the same query is made multiple times during execution, make adjustments immediately to improve application performance by reducing the time it takes to access the database.
When calling the database, PHP must wait for a response. For example 20 requests to the database will be slower than 15. try concatenating efficiently to 15 or smaller.

 

6. Avoid nested codes

When performing condition checks, sometimes we unconsciously use nested checks, this has an impact on the execution of your code, the time it takes to execute the code becomes inefficient, if you have a code structure like this:

if($car === 'ferrari')
{
    if($year === '2023')
    {
        if($color === 'red')
        {
            return true;
        }
    }
}

return false;

change it to this:

if($car !== 'ferrari') {
    return false;
}

if($year !== '2023') {
    return false;
}

if($color !== 'red') {
    return false;
}

return true;

 

6. Make sure the database is kept safe

Use mysql_real_escape_string() to apply to all databases, this will keep all strings from insecure and dangerous injection, other things never use global variable $_REQUEST, use POST or GET methods to send or receive data into query.


7. Use JSON for data exchange

JSON stands for JavaScript Object Notation and XML stands for Extensible Markup Language, and PHP itself has the json_encode and json_decode functions.

What does this function mean? json_encode is a function in PHP to convert PHP data format into JSON format and json_decode is a function in PHP to convert JSON format into PHP format.

We recommend using JSON in using data transfer so that it can be optimized properly compared to XML. The advantage of JSON is that it is easier to understand than XML.

XML format example

<root>
    <users>
        <username>John</username>
        <location>United States</location>
        <username>Doe</username>
        <location>California</location>
    </users>
</root>

JSON format example

{
    "users": [
        {
            "username": "John",
            "location": "United States"
        },
        {
            "username": "Doe",
            "location": "California"
        }
    ]
}

 

8. Take advantage of the native functions of PHP

If possible, use native PHP functions instead of writing your own functions manually.

It's also a good idea to learn in advance how to use PHP functions, try to take advantage of PHP's native functions instead of writing your own functions to achieve the same result. actually the function that we create manually is not necessary, we only use the original function from PHP.

To learn this not only helps in writing code faster, it also makes it more efficient.

 

Conclusion

By implementing this, of course, it will make our PHP website more optimal and supported by good security to maintain or protect user privacy from unwanted things. so, hopefully useful for all friends!

Share