• Время чтения ~3 мин
  • 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