Composer install error

A Dependency Manager for PHP
  • General
  • Package not found
  • Package is not updating to the expected version
  • Dependencies on the root package
  • 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)
  • 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#

  1. When facing any kind of problems using Composer, be sure to work with the
    latest version
    . See self-update for details.

  2. Before asking anyone, run composer diagnose to check
    for common problems. If it all checks out, proceed to the next steps.

  3. Make sure you have no problems with your setup by running the installer’s
    checks via curl -sS https://getcomposer.org/installer | php -- --check.

  4. Try clearing Composer’s cache by running composer clear-cache.

  5. 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 or composer.lock
    entries.

Package not found#

  1. Double-check you don’t have typos in your composer.json or repository
    branches and tag names.

  2. Be sure to set the right
    minimum-stability
    . To get started or be
    sure this is no issue, set minimum-stability to «dev».

  3. Packages not coming from Packagist should
    always be defined in the root package (the package depending on all
    vendors).

  4. 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.

  5. 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.

  6. 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:

  1. 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, the dev-main version will not satisfy it.
    The best solution here is to make sure you first define a branch alias.

  2. 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
    called COMPOSER_ROOT_VERSION. You set it to dev-main for example to define
    the root package’s version as dev-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.

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#

  1. Check the «Package not found» item above.

  2. 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 to 1.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 <...>

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)#

  1. Open regedit.
  2. Search for an AutoRun key inside HKEY_LOCAL_MACHINESoftwareMicrosoftCommand Processor,
    HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor
    or HKEY_LOCAL_MACHINESoftwareWow6432NodeMicrosoftCommand Processor.
  3. Check if it contains any path to a non-existent file, if it’s the case, remove them.

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:

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!

This is a list of common pitfalls on using Composer, and how to avoid them.

General

  1. When facing any kind of problems using Composer, be sure to work with the
    latest version
    . See self-update for details.

  2. Before asking anyone, run composer diagnose to check
    for common problems. If it all checks out, proceed to the next steps.

  3. Make sure you have no problems with your setup by running the installer’s
    checks via curl -sS https://getcomposer.org/installer | php -- --check.

  4. Try clearing Composer’s cache by running composer clear-cache.

  5. 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 or composer.lock
    entries.

Package not found

  1. Double-check you don’t have typos in your composer.json or repository
    branches and tag names.

  2. Be sure to set the right
    minimum-stability
    . To get started or be
    sure this is no issue, set minimum-stability to «dev».

  3. Packages not coming from Packagist should
    always be defined in the root package (the package depending on all
    vendors).

  4. 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.

  5. 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.

  6. 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:

  1. 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, the dev-main version will not satisfy it.
    The best solution here is to make sure you first define a branch alias.

  2. 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
    called COMPOSER_ROOT_VERSION. You set it to dev-main for example to define
    the root package’s version as dev-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.

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

  1. Check the «Package not found» item above.

  2. 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 to 1.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 <...>

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)

  1. Open regedit.
  2. Search for an AutoRun key inside HKEY_LOCAL_MACHINESoftwareMicrosoftCommand Processor,
    HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor
    or HKEY_LOCAL_MACHINESoftwareWow6432NodeMicrosoftCommand Processor.
  3. Check if it contains any path to a non-existent file, if it’s the case, remove them.

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.

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:

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 #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.

Это список распространенных «подводных камней» при использовании Composer,и как их избежать.

General

  1. При возникновении любых проблем с использованием Composer обязательно работайте с последней версией . Смотрите самообновление для деталей.

  2. Прежде чем спрашивать кого-либо, запустите composer diagnose , чтобы проверить наличие распространенных проблем. Если все в порядке, переходите к следующим шагам.

  3. Убедитесь, что у вас нет проблем с настройкой, запустив проверки установщика через curl -sS https://getcomposer.org/installer | php -- --check .

  4. Попробуйте очистить кэш Composer, запустив composer clear-cache Composer .

  5. Убедитесь, что вы устанавливаете поставщиков прямо из composer.json rm -rf vendor && composer update -v composer.json через rm -rf vendor && composer update -v при устранении неполадок, исключая любые возможные вмешательства в существующие установки поставщиков или записи composer.lock .

Пакет не найден

  1. Дважды проверьте, что у вас нет опечаток в вашем composer.json или ветках репозитория и именах тегов.

  2. Обязательно установите правильную минимальную стабильность . Чтобы начать работу или убедиться, что это не проблема, установите для параметра minimum-stability значение «dev».

  3. Пакеты не из Packagist всегда должны быть определены в корневом пакете (пакет зависит от всех поставщиков).

  4. Используйте одного и того же поставщика и имя пакета во всех ветвях и тегах вашего хранилища, особенно при поддержке стороннего ветвления и использовании replace .

  5. Если вы обновляетесь до недавно опубликованной версии пакета,имейте в виду,что у Packagist есть задержка до 1 минуты,прежде чем новые пакеты будут видны Composer.

  6. Если вы обновляете один пакет, это может зависеть от самой новой версии. В этом случае добавьте аргумент --with-dependencies или добавьте все зависимости, которые требуют обновления команды.

Пакет не обновляется до ожидаемой версии

Попробуйте запустить php composer.phar why-not [package-name] [expected-version] .

Зависимости от корневого пакета

Когда ваш корневой пакет зависит от пакета, который в конечном итоге зависит (прямо или косвенно) от самого корневого пакета, проблемы могут возникнуть в двух случаях:

  1. Во время разработки, если вы находитесь в ветке, такой как dev-main , и в ветке не определен псевдоним ветки , а для зависимости от корневого пакета требуется, например, версия ^2.0 dev-main ее не удовлетворит. Лучшее решение здесь — убедиться, что вы сначала определили псевдоним ветки.

  2. При выполнении CI (непрерывной интеграции) проблема может заключаться в том, что Composer не может правильно определить версию корневого пакета. Если это клон git, то, как правило, все в порядке, и Composer обнаружит версию текущей ветки, но некоторые CI делают неглубокие клоны, поэтому процесс может дать сбой при тестировании запросов на вытягивание и веток функций. В этих случаях псевдоним ветки может быть не распознан. Лучшее решение — определить версию, на которой вы работаете, с помощью переменной среды COMPOSER_ROOT_VERSION. Например, вы устанавливаете его в dev-main ,чтобы определить версию корневого пакета как dev-main . Используйте, например: COMPOSER_ROOT_VERSION=dev-main composer install чтобы экспортировать переменную только для вызова композитора, или вы можете определить ее глобально в CI env vars.

Пакет не найден в Дженкинс-билдинге.

  1. Проверьте пункт «Пакет не найден» выше.

  2. Git-clone/checkout внутри Jenkins оставляет ветку в состоянии «detached HEAD». В результате Composer может не определить версию текущей проверенной ветки и не разрешить зависимость от корневого пакета . Чтобы решить эту проблему, вы можете использовать «Дополнительные действия» -> «Извлечь в определенную локальную ветку» в настройках Git для вашей работы Jenkins, где ваша «локальная ветка» должна быть той же веткой, что и вы проверяете . Используя это, проверка больше не будет в отсоединенном состоянии, и зависимость от корневого пакета должна быть удовлетворена.

У меня есть зависимость,которая содержит определение «репозиториев» в его композиторе.json,но,похоже,его игнорируют.

Свойство конфигурации repositories определено как root- only repositories Это не наследуется. Подробнее о причинах этого можно прочитать в статье « Почему 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 использовал гораздо больше памяти, и обновление до последней версии даст вам гораздо лучшие и более быстрые результаты.

Иногда композитор может не справиться с некоторыми командами с этим сообщением:

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-подобных систем):

memory_limit = -1

Composer также учитывает ограничение памяти, определяемое переменной среды COMPOSER_MEMORY_LIMIT :

COMPOSER_MEMORY_LIMIT=-1 composer.phar <...>

Или вы можете увеличить лимит с помощью аргумента командной строки:

php -d memory_limit=-1 composer.phar <...>

Эта проблема также может возникать в случаях cPanel, когда активирована защита от бомбы-оболочки. Для получения дополнительной информации см. Документацию о функции вилочной бомбы на сайте cPanel.

Xdebug влияние на композитора

Чтобы повысить производительность при включенном расширении Xdebug, Composer автоматически перезапускает PHP без него. Вы можете изменить это поведение, используя переменную среды: COMPOSER_ALLOW_XDEBUG=1 .

Composer всегда будет показывать предупреждение, если используется Xdebug, но вы можете переопределить это с помощью переменной среды: COMPOSER_DISABLE_XDEBUG_WARN=1 . Если вы видите это предупреждение неожиданно, значит, процесс перезапуска завершился неудачно: сообщите об этой проблеме .

«Система не может найти указанный путь» (Windows)

  1. Open regedit.
  2. Найдите ключ AutoRun в HKEY_LOCAL_MACHINESoftwareMicrosoftCommand Processor , HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor или HKEY_LOCAL_MACHINESoftwareWow6432NodeMicrosoftCommand Processor .
  3. Проверьте, не содержит ли он пути к несуществующему файлу, если это так, удалите их.

API-ограничение скорости и маркеры OAuth

Из-за ограничения тарифов GitHub’а на их API может случиться так,что Composer запросит аутентификацию с запросом имени пользователя и пароля,чтобы он мог продолжить свою работу.

Если вы предпочитаете не предоставлять свои учетные данные GitHub в Composer, вы можете вручную создать токен, используя описанную здесь процедуру .

Теперь 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 заканчивается память и не включено пространство для подкачки.

free -m
total used free shared buffers cached
Mem: 2048 357 1690 0 0 237
-/+ buffers/cache: 119 1928
Swap: 0 0 0

Для включения подкачки можно,например,использовать:

/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

Вы можете сделать постоянный файл подкачки, следуя этому руководству .

proc_open():не удалось открыть потоковые ошибки (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 не включена. Дополнительные сведения см. В этом выпуске .

Degraded Mode

Из-за некоторых прерывистых проблем на 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.Если это невозможно,вы можете попробовать следующие обходные пути:

Workaround Linux:

Кажется, что в Linux выполнение этой команды помогает сделать трафик ipv4 более приоритетным, чем ipv6, что является лучшей альтернативой полному отключению ipv6:

sudo sh -c "echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf"

Workaround Windows:

На окнах единственный способ-полностью отключить ipv6,боюсь (либо в окнах,либо в домашнем роутере).

Обходной путь Mac OS X:

Получите имя вашего сетевого устройства:

networksetup -listallnetworkservices

Отключите IPv6 на этом устройстве (в данном случае «Wi-Fi»):

networksetup -setv6off Wi-Fi

Запустите Композитор…

Вы можете снова включить IPv6 с помощью:

networksetup -setv6automatic Wi-Fi

Тем не менее, если это решит вашу проблему, обратитесь к своему интернет-провайдеру, чтобы попытаться устранить ошибки маршрутизации. Это лучший способ решить проблемы для всех.

Композитор зависает с 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

2.4

  • Урегулирование конфликтов слияний

  • Scripts

  • Vendor binaries and the vendor/bin directory

  • Versions and constraints

Why Composer? #

Like any modern PHP application, Craft CMS manages dependencies with Composer. (If you’ve used npm, it’s a similar idea for PHP.)

If you’re new to package managers in general, Composer may first seem like a cumbersome and frustrating tool because of its tendency to get stuck on incompatibilities and errors. This is actually Composer’s primary benefit; it exposes software conflicts before updates are applied, rescuing clients, customers, and visitors from errors that never had a chance to happen in production.

What Composer Does #

Composer looks for a valid composer.json file that describes the PHP packages you intend to use in your project—that’s what the all-important require section is for, while require-dev describes a subset of items meant strictly for development and testing rather than production use.

These packages will be installed in your project’s vendor/ directory, and you’ll see more items there than you specified in your composer.json file because each of your required packages may also require dependencies of its own. Managing all these packages and requirements safely is exactly the problem Composer is designed to solve.

When you run composer update, composer traverses the complex web of dependencies to update packages according to your constraints and those of every other dependency in the tree. If there are no conflicts, the relevant files in vendor/ are updated and composer.lock is written to record precisely what was downloaded and at what version.

Run composer show --tree to inspect the entire dependency map.

You can commit composer.lock and run composer install in production to pull down those already-safe updated dependencies in far less time than composer update would require. (More on that in Deployment Best Practices.)

While you don’t need to be a Composer expert to work with it, it’s important to understand how the subtle differences in version constraints can be important, as well as the implications for a project’s minimum-stability designation.

Update vs. Install #

Generally speaking, it’s best to run composer update in development where you can test and confirm that your updated packages behave as expected, committing composer.lock once you’re confident that set of packages is ready for other environments.

Unless there were errors running composer update, it will then be safe to pull that new composer.lock file into another environment and run composer install to read it and bring that environment’s vendor/ folder up to date.

Both composer.json and composer.lock should be committed and deployed across environments.

Permissions Issues #

Systems may use different permissions setups, but Composer should always be run by whatever user normally executes PHP. If you’re seeing permissions issues, that is most likely the problem to solve.

Running Composer as a super user (i.e. with sudo) may force a certain action to succeed where it had previously failed, but you’ll want to be sure the resulting vendor/ directory has appropriate permissions so it doesn’t lead to further problems.

composer diagnose #

Running the composer diagnose terminal command gives you a quick sanity check. Consider using it to rule out more basic system-level problems:

$ composer diagnose
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
Composer version: 2.0.6
PHP version: 7.4.12
PHP binary path: /usr/local/Cellar/php/7.4.12/bin/php
OpenSSL version: OpenSSL 1.1.1h  22 Sep 2020
cURL version: 7.73.0 libz 1.2.11 ssl OpenSSL/1.1.1h
zip extension: OK

Common Composer Errors #

“Your requirements could not be resolved to an installable set of packages.” #

This is the most common message you’ll see with an update failure, and it will always be preceded by details that describe one or more dependency conflicts.

“No such file or directory in /autoload.php” #

Composer generates and updates a file named autoload.php an app like Craft can include once to load all its dependencies. Sometimes missing file errors mentioning autoload.php or autoload_real.php indicate an altered or corrupt vendor folder. In this case, it’s usually simplest to delete the vendor folder and reinstall all the dependencies:

rm -rf vendor/
composer install

“yiisoft/yii2-composer contains a Composer plugin which is currently not in your allow-plugins config.” #

Composer 2.2+ will show this error unless you add the following to your composer.json file’s config section:

"allow-plugins": {
   "craftcms/plugin-installer": true,
   "yiisoft/yii2-composer": true
},

This is included by default in new Craft CMS projects.

Further Reading #

  • Resolving PHP Requirement Conflicts

Работаю на framework’е Laravel 5. Добавляю пакет например "laravelcollective/html": "5.1.*" в composer.json, потом делаю composer install. А composer вводит мне:

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.
Nothing to install or update
Generating autoload files
> php artisan clear-compiled
> php artisan optimize
Generating optimized class loader

То есть ничего не устанавливает! Попробовал composer self-update не помогло. Потом composer update, добавил пакет в composer.json, потом еще раз попробовал composer install, никаких изменений все еще та же ошибка/информация вводится.

Раньше такого не было. Как исправить ситуацию?!

P.S. Пока что устанавливаю пакеты через composer requier <some_package_name> в terminal’е.

UPD:
Не которые предлагают выполнить команды composer update и composer requier, ни видно что они не очень поняли что я уже это делал. То есть:

  • Создал проект через laravel new <project_name>
  • Добавил в composer.json пакет "laravelcollective/html": "5.1.*"
  • Выполнил команду composer install, выводил то что я уже написал выше!
  • Потом удалил пакет из composer.json и выполнил composer update
  • Все прошло успешно
  • Потом опять добавил пакет в composer.json и выполнил composer install
  • Все те же сообщении
  • Потом опять удалил пакет из composer.json
  • Добавил пакет через composer requier, все прошло успешно
  • Потом другой пакет добавил в composer.json (barryvdh/laravel-debugbar), и выполнил команду composer install
  • Все те же сообщении…

When users tried to install or upgrade Laravel dependencies with composer install, an error “your requirements could not be resolved to an installable set of packages” occurs. Incompatibility between the Zizaco/entrust package and the Laravel version is the primary cause of the problem. Before the package upgrade, it was functioning properly, but now it is giving this problem.

Photo by Noelle Otto

 Table of Contents

  1. Explanation of “your requirements could not be resolved to an installable set of packages”.
  2. The root cause that can generate this error.
  3. Best possible solution.
  4. The conclusion.

Explanation of  Your requirements could not be resolved to an installable set of packages.

Best practices to understand an error message are dissecting the message into smaller parts as it is also a best practice while solving any problem as a software developer. Divide and rule is the best strategy to become a conqueror. Unfortunately, the scenario which we are discussing is not falling under this strategy because this message does not explain enough. When we thoroughly understand the message, it explains to us that some of our requirements would not be fulfilled with the package which we are installing.

What the actual is? The answer to this question is: that the dependency on branches is the cause of the issue. Most likely, when you were able to install your dependencies, the package Zizaco/entrust was using Laravel 4.2 in its main branch. You will never be able to execute composer updates and obtain updated dependencies, however, as soon as this branch is updated with an incompatible version need.

There is a version conflict with your software dependencies. Installing «Zizaco/entrust» from its master branch at the same time as Laravel’s version is what you want to do. Additionally, the Laravel version does not work with that master branch.

The root cause that can generate this error.

It is not possible that something happened without any reason. There must be a strong reason behind any issue that a user may experience working in any environment. Here is also the same, some reasons are considered the root cause of this error. If we dive deeply into the issue you can understand what is going on behind the scene. When we run the composer to install or upgrade a package or create a project that needs upgradation, the composer examines our installed PHP version with the PHP version restrictions from your composer when you execute install, update, need, or create-project (these will launch update). the PHP version prerequisites of your other dependencies, as well as the required field in JSON. Additionally, it verifies that a few optional PHP extensions are loaded and comply with both the required version and the PHP extension specifications of the necessary dependencies. When the versions conflict, the composer won’t install the necessary package packages for you.

The dependence on branches is the problem. It’s quite likely that you were able to install your dependencies at that time because the package zizaco/entrust once made use of Laravel 4.2 in its master branch. However, if this branch is updated with an incompatible version need, you will never be able to run composer updates and obtain updated dependencies.

In simple words, I can say the below-mentioned three points are the root cause that can generate this error message.

  • Your version of Laravel does not support the necessary package.
  • obsolete composer.lock file
  • The package name contains an error

Best possible solution.

Composer is used by Laravel to handle its dependencies. Download a copy of the composer.phar first. Once you have the PHAR archive, you can utilize it across your entire system by moving it to usr/local/bin or keeping it in your local project directory. You can utilize the Composer Windows installation for Windows.

The phar install (or composer install) command should be used to install every dependency needed by the framework. To complete the installation, Git must be installed on the server. The PHP composer command can be used to update the Laravel framework.

The error «Your requirements could not be resolved to an installable set of packages» in Laravel has a simple remedy.

Simply execute the next command if you are willing to install any package

 composer install --ignore-platform-reqs 

or if you are updating any package then use the below command

 composer update --ignore-platform-reqs 

Use labeled versions at all times! You should ideally utilize a lenient version requirement that permits compatible updates. As a tilde-two-number version requirement, this should be stated: Versions 1.2.0 and higher (such as 1.2.99 or 1.2.100), as well as 1.3 and higher, would be installed by 1.2. If a specific patch release is required, Caret-three-number version 1.2.10 will install that version as well as versions 1.3 and higher.

  Instead of using the unstable state in the main branch, using this version requirement will enable you to use released versions and address the most recent version that is still compatible with Laravel 4.2. Version 1.2 would also be OK, so I think that would be zizaco/entrust version 1.3.0. You should use «zizaco/entrust»: «1.2».

Instead of using the unstable state in the main branch, using this version requirement will enable you to use released versions and address the most recent version that is still compatible with Laravel 4.2. Version 1.2 would also be OK, so I think that would be zizaco/entrust version 1.3.0. You should use «zizaco/entrust»: «1.2».

The Conclusion

The error “your requirements could not be resolved to an installable set of packages” is a common issue of Laravel, specifically, when installing dependencies. It may take place more specifically with Ziazco/entrust packages because of incompatibilities with the Laravel version. The reason may differ, spelling mistakes also can cause this error or the outdated phar or composer, whatever the name you would like to use file may be one reason for this error. The solution to the error is very simple, first download and install the latest and compatible version of phar/composer for Laravel, then install or update any package with the command which will guide phar/composer to ignore prerequisites while installing, updating, or creating any package. Before going to any solution must use the relaxed version of Laravel dependencies and packages.

We are always keen to listen to our readers with their feedback and comments below in the comment section or through the feedback page. Comments and suggestions are always helpful to provide the best information.

Are you looking to fix the “Composer installation failed deleting ./composer.json file” error?

Lack of enough server resources, missing package links, etc. are the common reasons for Composer installation failures.

At Bobcares, we often get requests to fix Composer errors, as a part of our Server Management Services.

Today, let’s see a brief guide on how our Support Engineers fixed the Composer error.

What is Composer?

Before getting into the error details, let’s have a quick look at the Composer.

The Composer is an application-level package manager. Installing PHP based applications like the Laravel framework, Doctrine, etc. requires some dependency installation and updates.

Composer makes the task of dependency management easier by checking and installing the required packages with appropriate versions.

Reasons for Installation failed deleting ./composer.json error

To use a Composer for any project, it needs a composer.json file. This file tells the Composer to download the needed dependencies. This file is usually auto-generated while adding any dependency using the require command.

But sometimes while executing the command composer require <package name> the installation fails. Then it shows the error message as “Installation failed deleting ./composer.json”. It displays the exact reason for the error along with it. It can be due to incorrect package links, memory constraints and many more.

Recently, a customer approached us to fix an error he got while installing the Composer. The customer was trying to install the Laravel framework. And the error message appeared as,

Installation failed deleting ./composer.json

Here the error message specifies that there is no enough space, hence it checked for the swap. As there was no memory space and swap, the Composer installation failed.

Now let’s see how our Support Engineers fixed this error.

How we fix the error “Installation failed deleting ./composer.json”?

So far we have seen the reason for the error. Here, the error clearly says that the server is lacking memory for the installation. And one way to resolve this error is to allocate more memory.

Initially, when we get such an error our Support Engineers check the available resources in the server. We check this using the free -m command. This gives a complete picture of both memory and the swap space in the server.

If the server lacks memory space, we ask the customer to add more RAM space.

However, adding more RAM may not be possible in all scenarios. Alternatively, by checking the server space we can also allocate swap space. Usually, this can complete the Composer installation.

Allocating swap space can be recommended when the memory requirement is only for initialization. But this has a downside of slowing down the server.

Here, in this case, our Support Engineers analyzed the server space, memory usage, and performance of the server. Later, we suggested the customer add more RAM to the server. This solved the error and Composer started working fine.

In many error scenarios, the exact reason will be PHP version or missing modules, non-existing package URLs, etc. Therefore, the fix involves installing the missing modules, using valid package URLs in Composer.

[Still, having trouble in fixing Composer errors? – We can help you.]

Conclusion

In short, Composer installation failed deleting ./composer.json error happens due to lack of enough server memory, incorrect package links, etc. Today, we saw how our Support Engineers troubleshoot and fix this error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Понравилась статья? Поделить с друзьями:
  • Component mscomct2 ocx or one of its dependencies not correctly registered как исправить
  • Component error code 1639
  • Complete error vba
  • Complete error variable not defined
  • Complete error user defined type not defined