• Час читання ~4 хв
  • 07.08.2023

Чому обмеження пам'яті PHP важливі для вашого шляху розробки веб-сайту? PHP - це відома технологія бекенда, яка використовується багатьма технологічними гігантами для підтримки своїх додатків. PHP надає багато розширених функцій для того, щоб зробити веб-сторінки динамічними та інтегрувати деякі функції, які ви не можете просто отримати за допомогою JavaScript, HTML та CSS.

Кожного разу, коли ви налаштовуєте новий проект PHP, деяка пам'ять виділяється автоматично. Ця пам'ять в основному підходить для загальних застосувань. Але є деякі випадки, наприклад, коли ви завантажуєте важкі зображення, коли ваш веб-сайт використовує високу графіку, ви отримуєте деякі помилки, такі як -і Найкращий спосіб вирішити цю помилку - зв'язатися з хостинг-провайдером

“Fatal error: Allowed memory size of xxxxxx bytes exhausted”

і

“filename.jpg exceeds the maximum upload size for this site.”

The best way to solve this error is to contact the hosting provider і increase the memory limit of the application. But there are ways to increase the memory limit of the whole website or a particular script without any expert help like using php.ini file, .htacess file, etc. In this blog, we will discuss the various strategies for increasing memory limit і the benefits of increasing the memory limit of your PHP application.

Що таке обмеження пам'яті PHP?

Обмеження пам'яті PHP - це пам'ять сценарію, відведена для сценарію PHP. Це те саме, що ліміт зберігання, який може займати певне завдання. Це обмеження пам'яті в PHP-скриптах корисно в деяких випадках. Наприклад, можуть бути випадки, коли якийсь погано написаний код намагається з'їсти всю пам'ять в стеку.

Most WordPress websites have a memory limit of 32M, but you may require more memory in many cases. For example, if you are doing heavy operations like recurring calls to the database і heavy image processing, you need to increase the memory limit of your script.

Стратегії, які слід розглянути У

цій частині блогу ми поділимося різними способами збільшення лімітів пам'яті ваших сценаріїв / додатків PHP. Хоча це не єдині способи збільшити межі пам'яті вашого сценарію PHP, це ідеальні кроки, які більшість розробників використовують для проблем з обмеженням пам'яті.

Крім того, зміна ліміту пам'яті програми іноді може створити проблеми, тому ви завжди повинні створювати резервні копії даних вашої системи.

Перш ніж намагатися збільшити пам'ять, ви завжди повинні поговорити з постачальниками серверів вашого веб-сайту. Вони можуть допомогти вам збільшити ліміт пам'яті, використовуючи свої найкращі методи.

Стратегія 1: Відредагуйте файл

The php.ini file is executed every time a PHP application runs, і it’s used for controlling the various settings of PHP script like maximum upload size, memory limit, timeout limit, etc.

To increase the memory limit, you can change the following variables. But beware, these variables are case sensitive, і you need to restart the server after doing changes for them to be reflected.

memory_limit = 256M
upload_max_filesize = 12M
post_max_size = 13M
file_uploads = On
max_execution_time = 180

The max execution time refers to the timeout of the PHP script, і it means the maximum time for which the screen can be run.

Стратегія 2: Редагувати файл

HTAccess Файл .htacess є секретним файлом, тому його назва починається з крапки. Якщо ви користуєтеся віртуальним хостингом або з якихось причин не можете отримати доступ до файлу php.ini, вам необхідно відредагувати файл .htacess, щоб збільшити ліміт пам'яті.

Існують різні випадки використання цього файлу .htacess. До цього файлу потрібно додати наступні рядки, щоб збільшити ліміт пам'яті.

php_value memory_limit 256M
php_value upload_max_filesize 12M
php_value post_max_size 13M

Стратегія 3: Збільшення за допомогою функції

The ini_set() function is used to set the value of a particular attribute in the script's context only. It is considered the safest of all the above ways because it only sets the value for the script particularly і restricts the poorly written scripts from consuming all the memory on the server.

Щоб використовувати цю функцію для збільшення межі пам'яті, можна просто зробити.

ini_set('memory_limit', '512MB');

The above function will set the memory limit at 512 MB. Also, the ini_set() function is used only to set the value of a variable temporarily; once you close the script і restart it, it will take original values from the php.ini file.

Ключові висновки

There are many common errors like this memory limit one. In this blog, we have discussed the different strategies for increasing the memory limit in your script. The point to be noted here is that you should always raise the memory limit of your PHP script only as a last resort because this is a crucial task і can impact your site in many ways.

By the way, after making your website live to the actual customers, you must want to know what your users are doing on your website і the difficulties they are facing. It will help in increasing engagement і customer retention also. Scout APM is the best modern solution for the monitoring of your PHP application. It comes with support for many languages like PHP, Ruby, Python, etc. You will get 24x7 customer service, і pricing is very low compared to the market competitors.

Ми також пропонуємо 14-денну безкоштовну пробну версію без кредитної картки. Тож якщо ви хочете розширити свій бізнес на новий рівень, почніть безкоштовну пробну версію зараз!

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

Про мене

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

Про автора CrazyBoy49z
WORK EXPERIENCE
Контакти
Ukraine, Lutsk
+380979856297