- General
- Package not found
- Package is not updating to the expected version
- Dependencies on the root package
- Root package version detection
- Network timeout issues, curl error
- Package not found in a Jenkins-build
- I have a dependency which contains a «repositories» definition in its composer.json, but it seems to be ignored.
- I have locked a dependency to a specific commit but get unexpected results.
- Need to override a package version
- Figuring out where a config value came from
- Memory limit errors
- Xdebug impact on Composer
- «The system cannot find the path specified» (Windows)
- SSL certificate problem: unable to get local issuer certificate
- API rate limit and OAuth tokens
- proc_open(): fork failed errors
- proc_open(): failed to open stream errors (Windows)
- Degraded Mode
- Operation timed out (IPv6 issues)
- Composer hangs with SSH ControlMaster
- Zip archives are not unpacked correctly.
- Disabling the pool optimizer
This is a list of common pitfalls on using Composer, and how to avoid them.
General#
-
When facing any kind of problems using Composer, be sure to work with the
latest version. See self-update for details. -
Before asking anyone, run
composer diagnose
to check
for common problems. If it all checks out, proceed to the next steps. -
Make sure you have no problems with your setup by running the installer’s
checks viacurl -sS https://getcomposer.org/installer | php -- --check
. -
Try clearing Composer’s cache by running
composer clear-cache
. -
Ensure you’re installing vendors straight from your
composer.json
via
rm -rf vendor && composer update -v
when troubleshooting, excluding any
possible interferences with existing vendor installations orcomposer.lock
entries.
Package not found#
-
Double-check you don’t have typos in your
composer.json
or repository
branches and tag names. -
Be sure to set the right
minimum-stability. To get started or be
sure this is no issue, setminimum-stability
to «dev». -
Packages not coming from Packagist should
always be defined in the root package (the package depending on all
vendors). -
Use the same vendor and package name throughout all branches and tags of
your repository, especially when maintaining a third party fork and using
replace
. -
If you are updating to a recently published version of a package, be aware that
Packagist has a delay of up to 1 minute before new packages are visible to Composer. -
If you are updating a single package, it may depend on newer versions itself.
In this case add the--with-dependencies
argument or add all dependencies which
need an update to the command.
Package is not updating to the expected version#
Try running php composer.phar why-not [package-name] [expected-version]
.
Dependencies on the root package#
When your root package depends on a package which ends up depending (directly or
indirectly) back on the root package itself, issues can occur in two cases:
-
During development, if you are on a branch like
dev-main
and the branch has no
branch-alias defined, and the dependency on the root package
requires version^2.0
for example, thedev-main
version will not satisfy it.
The best solution here is to make sure you first define a branch alias. -
In CI (Continuous Integration) runs, the problem might be that Composer is not able
to detect the version of the root package properly. If it is a git clone it is
generally alright and Composer will detect the version of the current branch,
but some CIs do shallow clones so that process can fail when testing pull requests
and feature branches. In these cases the branch alias may then not be recognized.
The best solution is to define the version you are on via an environment variable
calledCOMPOSER_ROOT_VERSION
. You set it todev-main
for example to define
the root package’s version asdev-main
.
Use for example:COMPOSER_ROOT_VERSION=dev-main composer install
to export
the variable only for the call to composer, or you can define it globally in the
CI env vars.
Root package version detection#
Composer relies on knowing the version of the root package to resolve
dependencies effectively. The version of the root package is determined
using a hierarchical approach:
-
composer.json Version Field: Firstly, Composer looks for a
version
field in the project’s rootcomposer.json
file. If present, this field
specifies the version of the root package directly. This is generally not
recommended as it needs to be constantly updated, but it is an option. -
Environment Variable: Composer then checks for the
COMPOSER_ROOT_VERSION
environment variable. This variable can be explicitly set by the user to
define the version of the root package, providing a straightforward way to
inform Composer of the exact version, especially in CI/CD environments or
when the VCS method is not applicable. -
Version Control System (VCS) Inspection: Composer then attempts to guess
the version by interfacing with the version control system of the project. For
instance, in projects versioned with Git, Composer executes specific Git
commands to deduce the project’s current version based on tags, branches, and
commit history. If a.git
directory is missing or the history is incomplete
because CI is using a shallow clone for example, this detection may fail to find
the correct version. -
Fallback: If all else fails, Composer uses
1.0.0
as default version.
Note that relying on the default/fallback version might potentially lead to dependency
resolution issues, especially when the root package depends on a package which ends up
depending (directly or indirectly)
back on the root package itself.
Network timeout issues, curl error#
If you see something along the lines of:
Failed to download * curl error 28 while downloading * Operation timed out after 300000 milliseconds
It means your network is probably so slow that a request took over 300seconds to complete. This is the
minimum timeout Composer will use, but you can increase it by increasing the default_socket_timeout
value in your php.ini to something higher.
Package not found in a Jenkins-build#
-
Check the «Package not found» item above.
-
The git-clone / checkout within Jenkins leaves the branch in a «detached HEAD»-state. As
a result, Composer may not able to identify the version of the current checked out branch
and may not be able to resolve a dependency on the root package.
To solve this problem, you can use the «Additional Behaviours» -> «Check out to specific local
branch» in your Git-settings for your Jenkins-job, where your «local branch» shall be the same
branch as you are checking out. Using this, the checkout will not be in detached state any more
and the dependency on the root package should become satisfied.
I have a dependency which contains a «repositories» definition in its composer.json, but it seems to be ignored.#
The repositories
configuration property is defined as root-only. It is not inherited. You can read more about the reasons behind this in the «why can’t
Composer load repositories recursively?» article.
The simplest work-around to this limitation, is moving or duplicating the repositories
definition into your root
composer.json.
I have locked a dependency to a specific commit but get unexpected results.#
While Composer supports locking dependencies to a specific commit using the #commit-ref
syntax, there are certain
caveats that one should take into account. The most important one is documented, but
frequently overlooked:
Note: While this is convenient at times, it should not be how you use
packages in the long term because it comes with a technical limitation. The
composer.json metadata will still be read from the branch name you specify
before the hash. Because of that in some cases it will not be a practical
workaround, and you should always try to switch to tagged releases as soon
as you can.
There is no simple work-around to this limitation. It is therefore strongly recommended that you do not use it.
Need to override a package version#
Let’s say your project depends on package A, which in turn depends on a specific
version of package B (say 0.1). But you need a different version of said package B (say 0.11).
You can fix this by aliasing version 0.11 to 0.1:
composer.json:
{
"require": {
"A": "0.2",
"B": "0.11 as 0.1"
}
}
See aliases for more information.
Figuring out where a config value came from#
Use php composer.phar config --list --source
to see where each config value originated from.
Memory limit errors#
The first thing to do is to make sure you are running Composer 2, and if possible 2.2.0 or above.
Composer 1 used much more memory and upgrading to the latest version will give you much better and faster results.
Composer may sometimes fail on some commands with this message:
PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <...>
In this case, the PHP memory_limit
should be increased.
Note: Composer internally increases the
memory_limit
to1.5G
.
To get the current memory_limit
value, run:
php -r "echo ini_get('memory_limit').PHP_EOL;"
Try increasing the limit in your php.ini
file (ex. /etc/php5/cli/php.ini
for
Debian-like systems):
; Use -1 for unlimited or define an explicit value like 2G
memory_limit = -1
Composer also respects a memory limit defined by the COMPOSER_MEMORY_LIMIT
environment variable:
COMPOSER_MEMORY_LIMIT=-1 composer.phar <...>
Or, you can increase the limit with a command-line argument:
php -d memory_limit=-1 composer.phar <...>
However, please note that setting the memory limit using these methods primarily addresses memory issues within Composer itself and its immediate processes. Child processes or external commands invoked by Composer may still require separate adjustments if they have their own memory requirements.
This issue can also happen on cPanel instances, when the shell fork bomb protection is activated. For more information, see the documentation of the fork bomb feature on the cPanel site.
Xdebug impact on Composer#
To improve performance when the Xdebug extension is enabled, Composer automatically restarts PHP without it.
You can override this behavior by using an environment variable: COMPOSER_ALLOW_XDEBUG=1
.
Composer will always show a warning if Xdebug is being used, but you can override this with an environment variable:
COMPOSER_DISABLE_XDEBUG_WARN=1
. If you see this warning unexpectedly, then the restart process has failed:
please report this issue.
«The system cannot find the path specified» (Windows)#
- Open regedit.
- Search for an
AutoRun
key insideHKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor
,
HKEY_CURRENT_USER\Software\Microsoft\Command Processor
orHKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Command Processor
. - Check if it contains any path to a non-existent file, if it’s the case, remove them.
SSL certificate problem: unable to get local issuer certificate#
- Check that your root certificate store / CA bundle is up to date. Run
composer diagnose -vvv
and look forChecked CA file ...
orChecked directory ...
lines in the first lines of output.
This will show you where Composer is looking for a CA bundle. You can get a
new cacert.pem from cURL and store it there. - If this did not help despite Composer finding a valid CA bundle, try disabling your antivirus and
firewall software to see if that helps. We have seen issues where Avast on Windows for example would
prevent Composer from functioning correctly. To disable the HTTPS scanning in Avast you can go in
«Protection > Core Shields > Web Shield > uncheck Enable HTTPS scanning». If this helps you
should report it to the software vendor so they can hopefully improve things.
API rate limit and OAuth tokens#
Because of GitHub’s rate limits on their API it can happen that Composer prompts
for authentication asking your username and password so it can go ahead with its work.
If you would prefer not to provide your GitHub credentials to Composer you can
manually create a token using the procedure documented here.
Now Composer should install/update without asking for authentication.
proc_open(): fork failed errors#
If Composer shows proc_open() fork failed on some commands:
PHP Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar
This could be happening because the VPS runs out of memory and has no Swap space enabled.
free -m
total used free shared buffers cached
Mem: 2048 357 1690 0 0 237
-/+ buffers/cache: 119 1928
Swap: 0 0 0
To enable the swap you can use for example:
/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/bin/chmod 0600 /var/swap.1
/sbin/swapon /var/swap.1
You can make a permanent swap file following this tutorial.
proc_open(): failed to open stream errors (Windows)#
If Composer shows proc_open(NUL) errors on Windows:
proc_open(NUL): failed to open stream: No such file or directory
This could be happening because you are working in a OneDrive directory and
using a version of PHP that does not support the file system semantics of this
service. The issue was fixed in PHP 7.2.23 and 7.3.10.
Alternatively it could be because the Windows Null Service is not enabled. For
more information, see this issue.
Degraded Mode#
Due to some intermittent issues on Travis and other systems, we introduced a
degraded network mode which helps Composer finish successfully but disables
a few optimizations. This is enabled automatically when an issue is first
detected. If you see this issue sporadically you probably don’t have to worry
(a slow or overloaded network can also cause those time outs), but if it
appears repeatedly you might want to look at the options below to identify
and resolve it.
If you have been pointed to this page, you want to check a few things:
- If you are using ESET antivirus, go in «Advanced Settings» and disable «HTTP-scanner»
under «web access protection» - If you are using IPv6, try disabling it. If that solves your issues, get in touch
with your ISP or server host, the problem is not at the Packagist level but in the
routing rules between you and Packagist (i.e. the internet at large). The best way to get
these fixed is to raise awareness to the network engineers that have the power to fix it.
Take a look at the next section for IPv6 workarounds. - If none of the above helped, please report the error.
Operation timed out (IPv6 issues)#
You may run into errors if IPv6 is not configured correctly. A common error is:
The "https://getcomposer.org/version" file could not be downloaded: failed to
open stream: Operation timed out
We recommend you fix your IPv6 setup. If that is not possible, you can try the
following workarounds:
Generic Workaround:
Set the COMPOSER_IPRESOLVE=4
environment variable which will force curl to resolve
domains using IPv4. This only works when the curl extension is used for downloads.
Workaround Linux:
On linux, it seems that running this command helps to make ipv4 traffic have a
higher priority than ipv6, which is a better alternative than disabling ipv6 entirely:
sudo sh -c "echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf"
Workaround Windows:
On windows the only way is to disable ipv6 entirely I am afraid (either in windows or in your home router).
Workaround Mac OS X:
Get name of your network device:
networksetup -listallnetworkservices
Disable IPv6 on that device (in this case «Wi-Fi»):
networksetup -setv6off Wi-Fi
Run Composer …
You can enable IPv6 again with:
networksetup -setv6automatic Wi-Fi
That said, if this fixes your problem, please talk to your ISP about it to
try to resolve the routing errors. That’s the best way to get things resolved
for everyone.
Composer hangs with SSH ControlMaster#
When you try to install packages from a Git repository and you use the ControlMaster
setting for your SSH connection, Composer might hang endlessly and you see a sh
process in the defunct
state in your process list.
The reason for this is a SSH Bug: https://bugzilla.mindrot.org/show_bug.cgi?id=1988
As a workaround, open a SSH connection to your Git host before running Composer:
ssh -t git@mygitserver.tld
php composer.phar update
See also https://github.com/composer/composer/issues/4180 for more information.
Zip archives are not unpacked correctly.#
Composer can unpack zipballs using either a system-provided unzip
or 7z
(7-Zip) utility, or PHP’s
native ZipArchive
class. On OSes where ZIP files can contain permissions and symlinks, we recommend
installing unzip
or 7z
as these features are not supported by ZipArchive
.
Disabling the pool optimizer#
In Composer, the Pool
class contains all the packages that are relevant for the dependency
resolving process. That is what is used to generate all the rules which are then
passed on to the dependency solver.
In order to improve performance, Composer tries to optimize this Pool
by removing useless
package information early on.
If all goes well, you should never notice any issues with it but in case you run into
an unexpected result such as an unresolvable set of dependencies or conflicts where you
think Composer is wrong, you might want to disable the optimizer by using the environment
variable COMPOSER_POOL_OPTIMIZER
and run the update again like so:
COMPOSER_POOL_OPTIMIZER=0 php composer.phar update
Now double check if the result is still the same. It will take significantly longer and use
a lot more memory to run the dependency resolving process.
If the result is different, you likely hit a problem in the pool optimizer.
Please report this issue so it can be fixed.
Found a typo? Something is wrong in this documentation?
Fork and edit it!
Часто бывает так что при использовании Composer вы сталкиваетесь с ошибкой, что лимит памяти исчерпан.
И как следствие весь процесс выполнения падает.
Как же выйти из данный ситуации?
Оказывается очень просто.
Composer — это инструмент для управления зависимостями в PHP. Он позволяет вам объявить библиотеки, от которых зависит ваш проект, и он будет устанавливать или обновлять их для вас.
Но бывает так что при использовании composer вы сталкиваетесь с ошибкой, что лимит памяти исчерпан.
Fatal error: Allowed memory size of 1610612736 bytes exhausted in ...
Эта ошибка может возникать, особенно когда вы обновляете большие библиотеки или библиотеки с большим количеством зависимостей. Composer может быть довольно прожорлив к памяти.
Что же можно сделать в таком случае?
Прежде всего убедитесь, что Composer обновлен до последней версии
php composer.phar --self-update
После этого вы увеличить memory_limit
в PHP
Это можно сделать как через настройки самого PHP, так и сразу в консоли
php -d memory_limit=-1 composer.phar update ...
Так же можно убрать ограничение памяти для самого Composer
COMPOSER_MEMORY_LIMIT=-1 php composer.phar install
Если вы используете Docker для поднятия окружения, то можно лимиты прописать сразу в конфигурации
version: '3'
services:
php:
...
environment:
COMPOSER_MEMORY_LIMIT: -1
Для получения дополнительной информации обращайтесь к официальной документации: https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors
- Устранение неисправностей
- Общие сведения
- Пакет не найден
- Пакет не обновляется до ожидаемой версии
- Зависимости от корневого пакета
- Проблемы таймаута соединения, ошибка curl
- Пакет не найден в Jenkins-сборке
- У меня есть зависимость, которая содержит определение «repositories» в composer.json, но оно, похоже, игнорируется
- Я привязал зависимость к определённому коммиту, но получаю неожиданные результаты
- Необходимо переопределить версию пакета
- Определение того, откуда взялось значение конфигурации
- Ошибки ограничения памяти
- Влияние Xdebug на Composer
- «Система не может найти указанный путь» (Windows)
- Ограничение скорости работы API и токены OAuth
proc_open()
: fork failed errorsproc_open()
: failed to open stream errors (Windows)- Режим деградации
- Операция завершается по таймеру (проблемы с IPv6)
- Решение проблемы в Linux
- Решение проблемы в Windows
- Решение проблемы в Mac OS X
- Composer зависает при использовании SSH
ControlMaster
- Zip-архивы распаковываются некорректно
- Отключение оптимизатора пула
Устранение неисправностей
Ниже приведен список распространенных подводных камней при использовании Composer и способы их избежать.
Общие сведения
- При возникновении любых проблем с использованием Composer убедитесь, что вы работаете с последней стабильной версией. Подробности см. в разделе «Самообновление Composer«.
- Прежде чем обращаться к кому-либо за помощью, запустите команду
composer diagnose
, чтобы проверить наличие общих проблем. Если все подтвердилось, переходите к следующим шагам. - Убедитесь, что у вас нет проблем с установкой, запустив проверку программы установки через
curl -sS https://getcomposer.org/installer | php -- --check
. - Попробуйте очистить кэш Composer, выполнив команду
composer clear-cache
. - Убедитесь, что вы устанавливаете вендоров прямо из вашего
composer.json
с помощьюrm -rf vendor && composer update -v
при устранении неполадок, исключая любые возможные конфликты с существующими установками вендоров или записямиcomposer.lock
.
Пакет не найден
- Дважды проверьте, нет ли опечаток в вашем
composer.json
или ветках и названиях тегов репозитория. - Убедитесь, что установили правильное значение
minimum-stability
. Чтобы начать работу или убедиться, что это не проблема, установитеminimum-stability
на «dev
«. - Пакеты, не получаемые из Packagist, всегда должны быть определены в разделе корневого пакета (пакет, зависящий от всех поставщиков).
- Используйте одного и того же вендора и название пакета во всех ветках и тегах вашего репозитория, особенно при поддержке сторонних форков и использовании
replace
. - Если вы обновляете недавно опубликованную версию пакета, имейте в виду, что Packagist имеет задержку до 1 минуты, прежде чем новые пакеты станут видны Composer.
- Если вы обновляете отдельный пакет, он может сам зависеть от более новых версий. В этом случае добавьте аргумент
--with-dependencies
или добавьте в команду все зависимости, которые нуждаются в обновлении.
Пакет не обновляется до ожидаемой версии
Попробуйте выполнить php composer.phar why-not [package-name] [expected-version]
.
Зависимости от корневого пакета
Когда ваш корневой пакет зависит от пакета, который в итоге (прямо или косвенно) зависит от самого корневого пакета, проблемы могут возникнуть в двух случаях:
- Во время разработки, если вы находитесь в ветке, например
dev-main
, и в ней не определен псевдоним ветки, а зависимость от корневого пакета требует, например, версию^2.0
, то версияdev-main
не будет соответствовать ей. Лучшее решение здесь — убедиться, что вы предварительно определили псевдоним ветки. - При использовании CI (Continuous Integration) проблема может заключаться в том, что Composer не может правильно определить версию корневого пакета. Если это git-клон, то обычно всё в порядке, и Composer определит версию текущей ветки, но некоторые CI делают поверхностные клоны, поэтому этот процесс может не сработать при тестировании pull request’ов и ветвей фич. В таких случаях псевдоним ветки может быть не распознан. Лучшее решение — определять версию, в которой вы находитесь, с помощью переменной окружения
COMPOSER_ROOT_VERSION
. Установив ее, например, вdev-main
, вы определите версию корневого пакета какdev-main
. Используйте, например:COMPOSER_ROOT_VERSION=dev-main composer install
, чтобы экспортировать переменную только для вызова composer, или вы можете определить ее глобально в CI переменных окружения.
Проблемы таймаута соединения, ошибка curl
Если вы видите что-то вроде:
Failed to download * curl error 28 while downloading * Operation timed out after 300000 milliseconds
Это означает, что ваша сеть, вероятно, настолько медленная, что для выполнения запроса потребовалось более 300 секунд. Это минимальный таймаут, который будет использовать Composer, но его можно увеличить, увеличив значение default_socket_timeout
в вашем php.ini
.
Пакет не найден в Jenkins-сборке
- Посмотрите пункт «Пакет не найден» выше.
- При git-clone / checkout в Jenkins ветка остается в статусе «detached HEAD». В результате Composer может не определить версию текущей проверенной ветки и не разрешить зависимости от корневого пакета. Чтобы решить эту проблему, вы можете использовать «Additional Behaviours» -> «Check out to specific local branch» в настройках Git для вашего Jenkins-job, где ваша «локальная ветка» должна быть той же веткой, которую вы проверяете. В этом случае проверка больше не будет находиться в отделённом состоянии, а зависимость от корневого пакета должна быть реализована.
У меня есть зависимость, которая содержит определение «repositories» в composer.json, но оно, похоже, игнорируется.
Свойство конфигурации repositories
определено как root-only
. Оно не наследуется. Подробнее о причинах этого вы можете прочитать в статье «Почему Composer не может загружать репозитории рекурсивно?». Самым простым решением этой проблемы является перемещение или дублирование определения repositories
в корневой файл composer.json
.
Я привязал зависимость к определённому коммиту, но получаю неожиданные результаты.
Хотя Composer поддерживает привязку зависимостей к конкретному коммиту с помощью синтаксиса #commit-ref
, есть некоторые предостережения, которые следует принимать во внимание. Самое важное из них задокументировано, но часто упускается из виду:
Примечание: Несмотря на то, что в некоторых случаях это удобно, в долгосрочной перспективе использовать пакеты таким образом не следует, поскольку это связано с техническими ограничениями. Метаданные composer.json по-прежнему будут считываться из имени ветки, указанного перед хэшем. В связи с этим в некоторых случаях это не будет практичным обходным решением, и вы всегда должны стараться переходить на тегированные релизы как можно скорее.
Не существует простого обходного пути для устранения этого ограничения. Поэтому настоятельно рекомендуется не использовать его.
Необходимо переопределить версию пакета
Допустим, ваш проект зависит от пакета A, который, в свою очередь, зависит от определенной версии пакета B (скажем, 0.1). Но вам нужна другая версия этого пакета B (скажем, 0.11).
Вы можете решить эту проблему, заменив версию 0.11 на 0.1:
composer.json:
{
"require": {
"A": "0.2",
"B": "0.11 as 0.1"
}
}
См. раздел «Псевдонимы» для получения дополнительной информации.
Определение того, откуда взялось значение конфигурации
Используйте php composer.phar config --list --source
, чтобы увидеть, откуда взялось каждое значение конфигурации.
Ошибки ограничения памяти
Прежде всего убедитесь, что вы используете Composer 2, а по возможности — 2.2.0 или выше.
Composer 1 использовал гораздо больше памяти, и обновление до последней версии даст вам гораздо лучшие и быстрые результаты.
Иногда при выполнении некоторых команд Composer может выдать следующее сообщение:
PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <...>
В этом случае следует увеличить значение PHP memory_limit
.
Примечание: Composer самостоятельно расширяет значение
memory_limit
до1,5G
.
Чтобы получить текущее значение memory_limit
, выполните команду:
php -r "echo ini_get('memory_limit').PHP_EOL;"
Попробуйте увеличить лимит в файле php.ini
(например, /etc/php5/cli/php.ini
для Debian-подобных систем):
; Use -1 for unlimited or define an explicit value like 2G
memory_limit = -1
Composer также соблюдает ограничение памяти, определяемое переменной окружения COMPOSER_MEMORY_LIMIT
:
COMPOSER_MEMORY_LIMIT=-1 composer.phar <...>
Или вы можете увеличить лимит с помощью аргумента в командной строке:
php -d memory_limit=-1 composer.phar <...>
Однако обратите внимание, что установка лимита памяти с помощью этих методов в первую очередь решает проблемы с памятью в самом Composer и его непосредственных процессах. Для дочерних процессов или внешних команд, вызываемых Composer, может потребоваться отдельная настройка, если они имеют свои собственные требования к памяти.
Эта проблема также может возникнуть в среде cPanel, когда активирована защита от shell fork bomb. Для получения дополнительной информации см. документацию по функции » fork bomb» на сайте cPanel.
Влияние Xdebug на Composer
Чтобы повысить производительность при включении расширения Xdebug, Composer автоматически перезапускает PHP без него. Вы можете переопределить это поведение, используя переменную окружения: COMPOSER_ALLOW_XDEBUG=1
.
Composer всегда будет показывать предупреждение, если используется Xdebug, но вы можете переопределить это с помощью переменной окружения: COMPOSER_DISABLE_XDEBUG_WARN=1
. Если вы внезапно получили это предупреждение, значит, процесс перезапуска завершился неудачно: пожалуйста, сообщите об этом.
«Система не может найти указанный путь» (Windows)
- Откройте regedit.
- Найдите ключ
AutoRun
вHKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor
,HKEY_CURRENT_USER\Software\Microsoft\Command Processor
илиHKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Command Processor
. - Проверьте, не содержит ли он пути к несуществующим файлам, если это так, удалите их.
Ограничение скорости работы API и токены OAuth
Из-за ограничений GitHub на скорость работы API может случиться так, что Composer запросит аутентификацию, запросив ваше имя пользователя и пароль, чтобы продолжить работу.
Если вы предпочитаете не предоставлять Composer свои учетные данные GitHub, вы можете вручную создать токен, используя процедуру, описанную здесь.
Теперь Composer сможет устанавливать/обновлять без запроса аутентификации.
proc_open()
: fork failed errors
Если Composer показывает, что форк proc_open()
не выполнен для некоторых команд:
PHP Fatal error: Uncaught exception 'ErrorException' with message 'proc_open(): fork failed - Cannot allocate memory' in phar
Это может происходить из-за того, что на VPS не хватает памяти и не включен режим Swap space.
free -m
total used free shared buffers cached
Mem: 2048 357 1690 0 0 237
-/+ buffers/cache: 119 1928
Swap: 0 0 0
Чтобы включить swap, например, можно использовать:
/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/bin/chmod 0600 /var/swap.1
/sbin/swapon /var/swap.1
Создать постоянный файл swap можно, следуя этому руководству.
proc_open()
: failed to open stream errors (Windows)
Если Composer показывает ошибки proc_open(NUL)
в Windows:
proc_open(NUL): failed to open stream: No such file or directory
Это может происходить из-за того, что вы работаете в каталоге OneDrive и используете версию PHP, которая не поддерживает семантику файловой системы этого сервиса. Проблема была исправлена в версиях PHP 7.2.23 и 7.3.10.
Также проблема может быть связана с тем, что не включена служба Windows Null Service. Для получения дополнительной информации смотрите этот материал.
Режим деградации
Из-за периодически возникающих проблем в Travis и других системах был введен режим деградации сети, который помогает Composer успешно завершить работу, но отключает некоторые оптимизации. Он включается автоматически при первом обнаружении проблемы. Если вы наблюдаете эту проблему время от времени, вам, вероятно, не стоит беспокоиться (медленная или перегруженная сеть также может вызывать такие тайм-ауты), но если она возникает постоянно, вам стоит обратить внимание на приведенные ниже варианты ее выявления и устранения.
Если вы попали на эту страницу, вам нужно проверить несколько вещей:
- Если вы используете антивирус ESET, зайдите в «Дополнительные настройки» и отключите «HTTP-сканер» в разделе «Защита веб-доступа».
- Если вы используете IPv6, попробуйте отключить его. Если это решит ваши проблемы, свяжитесь с вашим провайдером или хостером сервера, проблема не на уровне Packagist, а в правилах маршрутизации между вами и Packagist (т.е. в настройках сети в целом). Лучший способ добиться их устранения — привлечь внимание сетевых инженеров, которые могут это исправить. Посмотрите следующий нижу раздел об обходных путях для IPv6.
- Если ничего из вышеперечисленного не помогло, сообщите об ошибке.
Операция завершается по таймеру (проблемы с IPv6)
Вы можете столкнуться с ошибками, если IPv6 настроен неправильно. Распространенной ошибкой является:
The "https://getcomposer.org/version" file could not be downloaded: failed to
open stream: Operation timed out
Мы рекомендуем исправить настройки IPv6. Если это невозможно, вы можете попробовать следующие обходные пути:
Решение проблемы в Linux
В Linux, похоже, выполнение этой команды помогает сделать трафик ipv4 имеющим более высокий приоритет, чем ipv6, что является лучшей альтернативой, чем полное отключение ipv6:
sudo sh -c "echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf"
Решение проблемы в Windows
Боюсь, что на Windows единственный способ — полностью отключить ipv6 (либо в windows, либо в вашем домашнем маршрутизаторе).
Решение проблемы в Mac OS X
Получите имя сетевого устройства:
networksetup -listallnetworkservices
Отключите IPv6 на этом устройстве (в данном случае «Wi-Fi»):
networksetup -setv6off Wi-Fi
Запустите Composer …
Вы можете снова включить IPv6 с помощью:
networksetup -setv6automatic Wi-Fi
Тем не менее, если это решит вашу проблему, пожалуйста, поговорите об этом со своим провайдером, чтобы попытаться устранить ошибки маршрутизации. Это лучший способ решить проблему для всех.
Composer зависает при использовании SSH ControlMaster
Когда вы пытаетесь установить пакеты из Git-репозитория и используете настройку ControlMaster
для SSH-соединения, Composer может бесконечно зависать, а в списке процессов вы видите процесс sh
в состоянии defunct
.
Причиной этого является ошибка SSH: https://bugzilla.mindrot.org/show_bug.cgi?id=1988.
В качестве обходного пути откройте SSH-соединение с хостом Git перед запуском Composer:
ssh -t git@mygitserver.tld
php composer.phar update
См. также https://github.com/composer/composer/issues/4180 для получения дополнительной информации.
Zip-архивы распаковываются некорректно.
Composer может распаковывать zip-файлы с помощью системной утилиты unzip
или 7z
(7-Zip), либо с помощью собственного класса PHP ZipArchive
. В операционных системах, где ZIP-файлы могут содержать разрешения и симлинки, мы рекомендуем установить unzip
или 7z
, поскольку эти функции не поддерживаются ZipArchive
.
Отключение оптимизатора пула
В Composer класс Pool
содержит все пакеты, которые имеют отношение к процессу разрешения зависимостей. Именно он используется для генерации всех правил, которые затем передаются анализатору зависимостей. Чтобы повысить производительность, Composer пытается оптимизировать этот Pool
, удаляя бесполезную информацию о пакетах на ранних этапах.
Если все идет хорошо, вы не должны замечать никаких проблем с этим, но если вы столкнулись с неожиданным результатом, таким как неразрешимый набор зависимостей или конфликты, в которых, по вашему мнению, Composer ошибается, вы можете отключить оптимизатор с помощью переменной окружения COMPOSER_POOL_OPTIMIZER
и запустить обновление снова, как описано выше:
COMPOSER_POOL_OPTIMIZER=0 php composer.phar update
Теперь проверьте, не изменился ли результат. Процесс разрешения зависимостей займет значительно больше времени и потребует больше памяти.
Если результат отличается, скорее всего, вы столкнулись с проблемой в оптимизаторе пула. Пожалуйста, сообщите об этом, чтобы проблема была исправлена.
Перевод с английского официальной документации Composer:
https://getcomposer.org/doc/articles/troubleshooting.md
Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать!
- Composer update memory limit
- Increase memory limit for Composer
- PHP memory_limit – understanding and increasing this setting
- Increasing memory limit composer
- Composer: Easy memory limit troubleshooting
- How to Fix Composer Memory Issue
- PHP Fatal Error : Out Of Memory Windows 10 #5859
Composer update memory limit
$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update Althought, in my case
512mb is not enough ! Source : On Windows: set
COMPOSER_MEMORY_LIMIT=99999999999&& php -d memory_limit=-1 composer.phar
update You can change xx Value that you want. memory_limit=XX Share. Improve
this answer. Follow edited Dec 20, 2020 at
composer update
php -d memory_limit=512M composer update
COMPOSER_MEMORY_LIMIT=-1 composer update
$>which composer
/usr/local/bin/composer
$>php -d memory_limit=512M /usr/local/bin/composer update
...
COMPOSER_MEMORY_LIMIT=-1 composer require <package-name>
$ php -d memory_limit=512M /usr/local/bin/composer update
$ COMPOSER_MEMORY_LIMIT=512M php composer.phar update
set COMPOSER_MEMORY_LIMIT=99999999999&& php -d memory_limit=-1 composer.phar update
export COMPOSER_MEMORY_LIMIT=99999999999 && php -d memory_limit=-1 composer.phar update
sudo fallocate -l 4G /swapfile
sudo dd if=/dev/zero of=/swapfile bs=4096k count=1048
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
[[email protected]]:/# cd /var
[[email protected]]:/var# touch swap.img
[[email protected]]:/var# chmod 600 swap.img
[[email protected]]:/var# mkswap /var/swap.img
[[email protected]]:/var# dd if=/dev/zero of=/var/swap.img bs=4096k count=1000
[[email protected]]:/var# mkswap /var/swap.img
[[email protected]]:/var# swapon /var/swap.img
cat /proc/sys/vm/swappiness
memory_limit = -1
php -d memory_limit=-1 C:/ProgramData/ComposerSetup/bin/composer.phar update
memory_limit=XX
MacBook-Pro:asiu jack$ php --ini
Configuration File (php.ini) Path: /usr/local/etc/php/7.4
Loaded Configuration File: /usr/local/etc/php/7.4/php.ini
Scan for additional .ini files in: /usr/local/etc/php/7.4/conf.d
Additional .ini files parsed: /usr/local/etc/php/7.4/conf.d/ext-
opcache.ini,
/usr/local/etc/php/7.4/conf.d/php-memory-limits.ini
php composer.phar --self-update
COMPOSER_MEMORY_LIMIT=128MB php composer.phar update
php -d memory_limit=512M composer.phar update ...
COMPOSER_MEMORY_LIMIT=-1 composer update --ignore-platform-reqs
vagrant up
vagrant ssh
php --version # 7.4
php --ini # Shows path to the php.ini file that's loaded
cd /etc/php/7.4/cli # your PHP version. Each PHP version has a folder
sudo vi php.ini
; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit = -1
sudo vi /usr/local/etc/php/7.4/conf.d/php-memory-limits.ini
valet restart
<C:\>set COMPOSER_MEMORY_LIMIT=-1
<C:\>composer install exhausted/packages
variables:
- key: COMPOSER_MEMORY_LIMIT
value: -1
php -d memory_limit=-1 C:\\composer\\composer.phar install
composer self-update
composer update
sudo COMPOSER_MEMORY_LIMIT=2G php /opt/bitnami/php/bin/composer.phar update
Increase memory limit for Composer
To increase the memory limit for composer, you need to set an environment
variable named COMPOSER_MEMORY_LIMIT. It accepts similar values to
memory_limit in php.ini with -1 being “unlimited” memory (which …
COMPOSER_MEMORY_LIMIT=-1 composer install
PHP memory_limit – understanding and increasing this setting
To increase the PHP memory limit setting, edit your PHP.ini file. Increase the
default value (example: Maximum amount of memory a script …
This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server...
Fatal error: Allowed memory size of x bytes exhausted (tried to allocate x bytes) in /path/to/php/script
PHP Fatal error: Out of memory (allocated x) (tried to allocate x bytes) in /path/to/php/script
memory_limit = 256M
php_value memory_limit 256M
Increasing memory limit composer
I want to increase the memory limit of the composer environment variable. a
help file suggested this command » php -d memory_limit=-1 composer.phar » but
i tried to execute the command in the directory where composer is supposed to
be executing from, the file does not exist. so i am not sure where to find the
.phar file. which from i know is an …
php -d memory_limit=-1 composer
php -d memory_limit=-1 composer <...>
php -d memory_limit=-1 composer require apackage
php -d memory_limit=-1 composer update
Composer: Easy memory limit troubleshooting
The solution is to use the COMPOSER_MEMORY_LIMIT environment variable, setting
its value to -1. It can be added to the current Terminal session with. And it
will be used by all the composer commands you use in that session. Or it can
be used on-demand by those Composer commands you know they need more than the
memory_limit setting value you
$ php composer.phar require guzzlehttp/guzzle
Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes)...
$ export COMPOSER_MEMORY_LIMIT=-1
$ COMPOSER_MEMORY_LIMIT=-1 php composer.phar [command]
How to Fix Composer Memory Issue
To find out what the current memory limit is, run the following command: php
-r «echo ini_get (‘memory_limit’).PHP_EOL;» After running the command, this is
my current memory limit. 128M. Since the memory limit is 128M, it is a good
idea to increase it. To increase the memory limit, we need to locate the PHP
config file.
PHP Fatal error: Allowed memory size of XXXXXX bytes exhausted <...>
php -r "echo ini_get('memory_limit').PHP_EOL;"
128M
php --ini
Configuration File (php.ini) Path: /Applications/MAMP/bin/php/php7.0.8/conf
Loaded Configuration File: /Applications/MAMP/bin/php/php7.0.8/conf/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed: (none)
memory_limit = 512M;
php -r "echo ini_get('memory_limit').PHP_EOL;"
512M
PHP Fatal Error : Out Of Memory Windows 10 #5859
@alcohol I tried to raise the memory limit of the php.ini of Wamp Server 3.0.0
but when I restarted all services, the limit was still 128M (I wrote 1G),
however when I returned in the php.ini, there is my change. I don’t understand
So, I prefer to do it with a command line. But I still say that there is a
problem with composer and not with my install because in one year, …
...{
"name": "nenad/yii2-advanced-template",
"description": "Improved Yii 2 Advanced Application Template By Nenad Zivkovic",
"keywords": ["yii2", "framework", "advanced", "improved", "application template", "nenad"],
"type": "project",
"license": "BSD-3-Clause",
"support": {
"tutorial": "http://www.freetuts.org/tutorial/view?id=6",
"source": "https://github.com/nenad-zivkovic/yii2-advanced-template"
},
"minimum-stability": "stable",
"require": {
"php": ">=5.4.0",
"yiisoft/yii2": "*",
"yiisoft/yii2-bootstrap": "*",
"yiisoft/yii2-swiftmailer": "*",
"nenad/yii2-password-strength": "*",
"mihaildev/yii2-ckeditor": "*",
"mdmsoft/yii2-admin":"*"
},
"require-dev": {
"yiisoft/yii2-codeception": "*",
"yiisoft/yii2-debug": "*",
"yiisoft/yii2-gii": "*",
"yiisoft/yii2-faker": "*",
"codeception/specify": "*",
"codeception/verify": "*",
},
"config": {
"vendor-dir": "_protected/vendor",
"process-timeout": 1800
},
"extra": {
"asset-installer-paths": {
"npm-asset-library": "_protected/vendor/npm",
"bower-asset-library": "_protected/vendor/bower"
}
}
}
...
...Checking composer.json: WARNING
require.yiisoft/yii2 : unbound version constraints (*) should be avoided
require.yiisoft/yii2-bootstrap : unbound version constraints (*) should be avoided
require.yiisoft/yii2-swiftmailer : unbound version constraints (*) should be avoided
require.nenad/yii2-password-strength : unbound version constraints (*) should be avoided
require.mihaildev/yii2-ckeditor : unbound version constraints (*) should be avoided
Checking platform settings: OK
Checking git settings: OK
Checking http connectivity to packagist: OK
Checking https connectivity to packagist: OK
Checking github.com oauth access: OK
Checking disk free space: OK
Checking pubkeys:
Tags Public Key Fingerprint: 57815BA2 7E54DC31 7ECC7CC5 573090D0 87719BA6 8F3BB723 4E5D42D0 84A14642
Dev Public Key Fingerprint: 4AC45767 E5EC2265 2F0C1167 CBBB8A2B 0C708369 153E328C AD90147D AFE50952
OK
Checking composer version: OK...
...php composer.phar update...
...Loading composer repositories with package information
Updating dependencies (including require-dev)
PHP Fatal error: Out of memory (allocated 1966080000) (tried to allocate 32 bytes) in phar://F:/xampp/htdocs/Nxb/nxbrankings/composer.phar/src/Composer/DependencyResolver/Rule.php on line 60
Fatal error: Out of memory (allocated 1966080000) (tried to allocate 32 bytes) in phar://F:/xampp/htdocs/Nxb/nxbrankings/composer.phar/src/Composer/DependencyResolver/Rule.php on line 60...
$ cd path\of\my\project
$ php -d memory_limit=-1 C:\path\of\composer\ComposerSetup\bin\composer.phar require oneup/uploader-bundle "~1.4"
@myks92
Нашёл решение — пометь вопрос ответом!
Всем привет! У меня проблема с композером. Выдает лимит памяти. Во всех init файлах повысил лимит, но композер все равно выдает 128М. Что делать?
Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 268435464 bytes) in phar:///Users/maksimvorozcov/Web/eventdance/composer.phar/src/Composer/DependencyResolver/RuleSet.php on line 83
Check https://getcomposer.org/doc/articles/troubleshooti… for more info on how to handle out of memory errors.MBP-Maksim:eventdance maksimvorozcov$ php -d memory_limit=-1 composer.phar all
-
Вопрос задан
-
14830 просмотров
Во всех init файлах повысил лимит, но композер все равно выдает 128М
Надеюсь всё таки речь про ini файлы.
Видимо не угадали местоположение.
У меня тоже бывает несколько версий php на ПК и какая из них запустилась смотрю через process explorer (win)
Ну и как-бы в самом вопросе содержится ответ, запускайте с явным указанием пути к php и параметром memory_limit=-1
Пригласить эксперта
COMPOSER_MEMORY_LIMIT=-1 composer install
-
Показать ещё
Загружается…