Skip to content

Changing process environment unsafe on multithreaded servers #76

@toddbc

Description

@toddbc

When using Dotenv on a multithreaded webserver, such as through Apache on Windows with the winnt mpm or on Linux/Unix with an event or worker mpm, using putenv and getenv is actually unsafe.

This is because:

  1. The environment is per process. This means that two instances of PHP will share the same environment in a multithreaded server, rather than each using a unique one.
  2. The functions putenv() and getenv() are not required to be re-entrant or thread safe. What this means is that if two threads happen to call them at the same time (either on different cores, or from a context switch in the middle of the function), bad things can happen.
  3. putenv() (in C) takes a pointer and references the memory, rather than copying it (depending on implementation; on a Mac it does make a copy iirc, even though this violates the spec.) PHP keeps this around in a hash table, which is destroyed at the end of the request. This may cause the environment to be cleared while another thread is running and using it.

See laravel/framework#8187 for a deeper description of the effects of these problems.

The only real benefit of modifying the environment using putenv() is that forked child processes will inherit the environment. For the most part, modifying $_ENV would be enough (however, using getenv() would no longer be enough in that case.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions