> ## Documentation Index
> Fetch the complete documentation index at: https://developer.upsun.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PHP

> Deploy PHP apps on Upsun using PHP-FPM, FrankenPHP, or Swoole. Configure PHP extensions, tune FPM worker settings, enable Xdebug for debugging, and manage dependencies with Composer.

export const DynamicCodeBlock = ({language = 'yaml', filename, icon, lines, wrap, expandable, highlight, focus, children}) => {
  const STORAGE_KEY = 'upsun_versions_cache';
  const COMPOSABLE_STORAGE_KEY = 'upsun_composable_cache';
  const CACHE_TTL = 5 * 60 * 1000;
  const API_URL = 'https://meta.upsun.com/images';
  const COMPOSABLE_API_URL = 'https://meta.upsun.com/composable';
  const DEBUG_PREFIX = '[DynamicCodeBlock cache]';
  const [versionData, setVersionData] = useState(null);
  const [versionError, setVersionError] = useState(false);
  const [composableData, setComposableData] = useState(null);
  const [composableError, setComposableError] = useState(false);
  useEffect(() => {
    const fetchData = async () => {
      let cachedData = null;
      let cachedEtag = null;
      if (typeof localStorage !== 'undefined') {
        try {
          const cached = localStorage.getItem(STORAGE_KEY);
          if (cached) {
            const parsed = JSON.parse(cached);
            cachedData = parsed?.data || null;
            cachedEtag = parsed?.etag || null;
            if (cachedData && Date.now() - parsed.timestamp < CACHE_TTL) {
              return cachedData;
            }
          }
        } catch (err) {
          console.error('Failed to load from cache:', err);
        }
      }
      const requestHeaders = cachedEtag ? {
        'If-None-Match': cachedEtag
      } : {};
      console.debug(`${DEBUG_PREFIX} revalidating`, {
        storageKey: STORAGE_KEY,
        hasCachedData: Boolean(cachedData),
        hasCachedEtag: Boolean(cachedEtag)
      });
      const response = await fetch(API_URL, {
        headers: requestHeaders
      });
      if (response.status === 304 && cachedData) {
        console.debug(`${DEBUG_PREFIX} revalidated (304)`, {
          storageKey: STORAGE_KEY
        });
        if (typeof localStorage !== 'undefined') {
          try {
            const etag = response.headers.get('etag') || cachedEtag;
            localStorage.setItem(STORAGE_KEY, JSON.stringify({
              data: cachedData,
              etag,
              timestamp: Date.now()
            }));
          } catch (err) {
            console.error('Failed to refresh cache metadata:', err);
          }
        }
        return cachedData;
      }
      if (!response.ok) throw new Error(`API request failed: ${response.statusText}`);
      const data = await response.json();
      const etag = response.headers.get('etag');
      console.debug(`${DEBUG_PREFIX} refreshed (200)`, {
        storageKey: STORAGE_KEY,
        etag
      });
      if (typeof localStorage !== 'undefined') {
        try {
          localStorage.setItem(STORAGE_KEY, JSON.stringify({
            data,
            etag,
            timestamp: Date.now()
          }));
        } catch (err) {
          console.error('Failed to cache data:', err);
        }
      }
      return data;
    };
    fetchData().then(data => setVersionData(data)).catch(err => console.error('Failed to fetch version data:', err));
  }, []);
  const findHighestVersion = versionsMap => {
    if (!versionsMap || Object.keys(versionsMap).length === 0) return null;
    const entries = Object.entries(versionsMap);
    const active = entries.filter(([, v]) => v.upsun && v.upsun.status === 'supported' || v.upsun && v.upsun.status === 'deprecated');
    const candidates = active.length > 0 ? active : entries;
    let [highestName] = candidates[0];
    for (let i = 1; i < candidates.length; i++) {
      const [currentName] = candidates[i];
      const cp = currentName.split('.').map(Number);
      const hp = highestName.split('.').map(Number);
      for (let j = 0; j < Math.max(cp.length, hp.length); j++) {
        if ((cp[j] || 0) > (hp[j] || 0)) {
          highestName = currentName;
          break;
        } else if ((cp[j] || 0) < (hp[j] || 0)) {
          break;
        }
      }
    }
    return highestName;
  };
  const getVersion = (lang, requestedVersion = 'latest') => {
    if (lang === 'composable') {
      if (!composableData || !composableData.versions || Object.keys(composableData.versions).length === 0) return null;
      if (requestedVersion && requestedVersion !== 'latest') {
        return (requestedVersion in composableData.versions) ? requestedVersion : null;
      }
      return findHighestVersion(composableData.versions);
    }
    if (!versionData) return null;
    const imageData = versionData[lang];
    if (!imageData || !imageData.versions || Object.keys(imageData.versions).length === 0) {
      return null;
    }
    if (requestedVersion && requestedVersion !== 'latest') {
      return (requestedVersion in imageData.versions) ? requestedVersion : null;
    }
    return findHighestVersion(imageData.versions);
  };
  let code = typeof children === 'string' ? children : String(children || '');
  const codeLines = code.split('\n');
  while (codeLines.length > 0 && codeLines[0].trim() === '') codeLines.shift();
  while (codeLines.length > 0 && codeLines[codeLines.length - 1].trim() === '') codeLines.pop();
  if (codeLines.length > 0) {
    const indents = codeLines.filter(line => line.trim().length > 0).map(line => line.match(/^[ \t]*/)[0].length);
    const minIndent = Math.min(...indents);
    code = codeLines.map(line => line.slice(minIndent)).join('\n');
  }
  code = code.replace(/\{\{version:(.*?)\}\}/g, (match, params) => {
    const parts = params.split(':');
    const lang = parts[0];
    const ver = parts[1] || 'latest';
    const isComposable = lang === 'composable';
    const hasError = isComposable ? composableError : versionError;
    const dataReady = isComposable ? composableData !== null : versionData !== null;
    if (hasError) return '(unavailable)';
    if (dataReady) {
      const resolvedVersion = getVersion(lang, ver);
      return resolvedVersion || match;
    }
    return '...';
  });
  const codeBlockProps = {
    language,
    ...filename && ({
      filename
    }),
    ...icon && ({
      icon
    }),
    ...lines !== undefined && ({
      lines
    }),
    ...wrap !== undefined && ({
      wrap
    }),
    ...expandable !== undefined && ({
      expandable
    }),
    ...highlight && ({
      highlight
    }),
    ...focus && ({
      focus
    })
  };
  return <CodeBlock {...codeBlockProps}>{code}</CodeBlock>;
};

export const RepoList = ({lang, displayName}) => <Info>
    To deploy a {displayName} project, create a new project from the{' '}
    <a href="https://console.upsun.com/projects/create-project">Upsun Console</a>{' '}
    and select a template, or push your existing code.
  </Info>;

export const VersionDeprecatedBlock = () => <>
    <h3 id="deprecated-versions">Deprecated versions</h3>
    <p>
    The following versions are <a href="/docs/glossary#deprecated-versions">deprecated</a>.
    They're available, but they don't receive security updates from upstream and aren't guaranteed to work.
    They'll be removed in the future – consider migrating to a <a href="#supported-versions">supported version</a>.
    </p>
  </>;

export const VariableBlock = ({name}) => {
  return <var spellCheck={false} title={`Replace '${name}' with your own data`}>{name}</var>;
};

<Info>
  You can now use the Upsun [composable image](/docs/configure-apps/app-reference/composable-image) to install runtimes and tools in your application container.
  To find out more about this feature, see the [dedicated documentation page](/docs/configure-apps/app-reference/composable-image).<br />
  Also, see how you can [modify your PHP runtime when using the composable image](#modify-your-php-runtime-when-using-the-composable-image).
</Info>

## Supported versions

You can select the major and minor version.

Patch versions are applied periodically for bug fixes and the like. When you deploy your app, you always get the latest available patches.

* 8.5
* 8.4

Note that from PHP versions 7.1 to 8.1, the images support the Zend Thread Safe (ZTS) version of PHP.

### Specify the language

To use PHP, specify `php` as your [app's `type`](/docs/configure-apps/app-reference/single-runtime-image#type):

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        <APP_NAME>:
          type: 'php:<VERSION_NUMBER>'
    `
  }
</DynamicCodeBlock>

For example:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'`
  }
</DynamicCodeBlock>

<VersionDeprecatedBlock />

* 8.3
* 8.2

## Retired versions

The following versions have been retired and are no longer available.
If your project uses a retired version, you must update to a [supported version](#supported-versions).

* 8.1
* 8.0
* 7.4
* 7.3
* 7.2
* 7.1
* 7.0
* 5.6
* 5.5
* 5.4

## Usage example

Configure your app to use PHP on Upsun.

### 1. Specify the version

Choose a [supported version](#supported-versions)
and add it to your [app configuration](/docs/configure-apps):

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'`
  }
</DynamicCodeBlock>

### 2. Serve your app

To serve your app, define what (and how) content should be served by setting the [`locations` parameter](/docs/configure-apps/image-properties/web#locations).

Usually, it contains the two following (optional) keys:

* `root` for the document root,
  the directory to which all requests for existing `.php` and static files (such as `.css`, `.jpg`) are sent.
* `passthru` to [define a front controller](/docs/configure-apps/web/php-basic#set-different-rules-for-specific-locations) to handle nonexistent files.
  The value is a file path relative to the [app root](/docs/configure-apps/image-properties/source).

  <Note>
    For enhanced security, when setting `passthru` to `true`, you might also want to add the following configuration:

    1. Set `scripts` to `false`.
       This prevents PHP scripts from being executed from the specified location.

    2. Set `allow` to `false`.
       By default, when PHP scripts aren't executed, their source code is delivered.
       Setting `allow` to `false` allows you to keep the source code of your PHP scripts confidential.
  </Note>

Adjust the `locations` block to fit your needs.

In the following example, all requests made to your site's root (`/`) are sent to the `public` directory
and nonexistent files are handled by `app.php`:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          web:
            locations:
              '/':
                root: 'public'
                passthru: '/app.php'`
  }
</DynamicCodeBlock>

See how to [create a basic PHP app with a front controller](/docs/configure-apps/web/php-basic).
To have more control, you can define rules to specify which files you want to allow [from which location](/docs/configure-apps/web/php-basic#set-different-rules-for-specific-locations).

### Complete example

A complete basic app configuration looks like the following:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          web:
            locations:
              '/':
                root: 'public'
                passthru: '/app.php'`
  }
</DynamicCodeBlock>

## Dependencies

Up to PHP version 8.1, it's assumed that you're using [Composer](https://getcomposer.org/) 1.x to manage dependencies.
If you have a `composer.json` file in your code, the default [build flavor is run](/docs/configure-apps/app-reference/single-runtime-image#build):

```bash theme={null}
composer --no-ansi --no-interaction install --no-progress --prefer-dist --optimize-autoloader
```

Adding a dependency to the [dependencies block](/docs/configure-apps/app-reference/single-runtime-image#dependencies) makes it available globally.
So you can then use included dependencies as commands within your app container.
You can add multiple global dependencies to the dependencies block, such as [Node.js](/docs/languages/nodejs#2-specify-any-global-dependencies).

If you want to have more control over Composer or if you don't want to use Composer at all, adapt the [build flavor](#change-the-build-flavor).
You can also use a [private, authenticated third-party Composer repository](/docs/languages/php/composer-auth).

### Change the build flavor

If you need more control over the dependency management,
you can either use your custom build flavor
or interact with Composer itself through [its environment variables](https://getcomposer.org/doc/03-cli#environment-variables).

You can remove the default build flavor and run your own commands for complete control over your build.
Set the build flavor to `none` and add the commands you need to your `build` hook, as in the following example:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          <snip>
          build:
            flavor: none

          hooks:
            build: |
              set -e
              composer install --no-interaction --no-dev`
  }
</DynamicCodeBlock>

That installs production dependencies with Composer but not development dependencies.
The same can be achieved by using the default build flavor and [adding the `COMPOSER_NO_DEV` variable](/docs/development/variables/set-variables).

See more on [build flavors](/docs/configure-apps/app-reference/single-runtime-image#build).

### Alternative repositories

In addition to the standard `dependencies` format,
you can specify alternative repositories for Composer to use as global dependencies.
So you can install a forked version of a global dependency from a custom repository.

To install from an alternative repository:

1. Set an explicit `require` block:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          <snip>
          dependencies:
            php:
              require:
                "platformsh/client": "2.x-dev"`
  }
</DynamicCodeBlock>

This is equivalent to `composer require platform/client 2.x-dev`.

2. Add the repository to use:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          <snip>
          dependencies:
            php:
              require:
                "platformsh/client": "2.x-dev"
              repositories:
                - type: vcs
                  url: "git@github.com:platformsh/platformsh-client-php.git"`
  }
</DynamicCodeBlock>

That installs `platformsh/client` from the specified repository URL as a global dependency.

### Configure security blocking

When building a PHP app, Upsun runs `composer install`, which runs the latest available Composer version.

By default, PHP builds fail if a dependency in a project has a known vulnerability. A PHP build might also fail if a dependency is abandoned.

**The best practice is to upgrade the dependencies** to reduce security risks and to catch issues sooner. However, you can configure the level of security blocking by defining the following keys in the `.dependencies.php.config` section of your `.upsun/config.yaml` file.

| Key                     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `audit.block-insecure`  | Default is `true`. **Important: Upsun recommends keeping this default setting and upgrading affected dependencies to reduce security risks.**                                                                                                                                                                                                                                                                                                 |
| `audit.block-abandoned` | Default is `false`; set to `true` for even stricter security. Ignored if `audit.block-insecure` is `false`.                                                                                                                                                                                                                                                                                                                                   |
| `audit.ignore`          | Array of specific advisories to ignore; see example below.                                                                                                                                                                                                                                                                                                                                                                                    |
| `audit.ignore-severity` | Ignore vulnerabilities based on their severity rating (`low`/`medium`/`high`). See the example below.<br />For each rating, include an `apply` key with one of these values:<ul><li>`all` to ignore everything for this rating</li><li>`block` to ignore this severity level for blocking builds (but still flag findings in audit reports)</li><li>`audit` to ignore this severity level in audit reports (but still block builds)</li></ul> |

Examples:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          <snip>
          dependencies:
            php:
              config:
                audit:
                  ignore:  # ignore these security advisories
                    - "PKSA-yhcn-xrg3-68b1"
                    - "PKSA-2wrf-1mxk-1pky"`
  }
</DynamicCodeBlock>

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          <snip>
          dependencies:
            php:
              config:
                audit:
                  ignore-severity:
                    low:
                      apply: all   # ignore all low severity findings`
  }
</DynamicCodeBlock>

Related information:

* [Troubleshooting PHP builds that now fail](/docs/languages/php#configure-security-blocking)

### Additional Composer schema properties

In addition to [alternate repositories](#alternative-repositories), other
[Composer schema properties](https://getcomposer.org/doc/04-schema) can be added to the global dependencies. For
example, one of your dependencies may be a plugin where you need to explicitly whitelist it as an
[allowed-plugin](https://getcomposer.org/doc/06-config#allow-plugins).

To add additional composer schema properties:

1. Set an explicit `require` block:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          <snip>
          dependencies:
            php:
              require:
                "third-party/required-plugin"": "^3.0"`
  }
</DynamicCodeBlock>

2. Add each additional property as a block at the same indentation as the `require` block:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          <snip>
          dependencies:
            php:
              require:
                symfony/runtime: '*'
              config:
                "allow-plugins":
                  symfony/runtime: true`
  }
</DynamicCodeBlock>

## Connect to services

You can access service credentials to connect to [managed services](/docs/add-services) from environment variables present in the application container.
Consult each of the individual service documentation to see how to retrieve and surface credentials into your application.

* [ClickHouse](https://developer.upsun.com/docs/add-services/clickhouse#usage-example)
* [Elasticsearch](https://developer.upsun.com/docs/add-services/elasticsearch#usage-example)
* [Gotenberg](https://developer.upsun.com/docs/add-services/gotenberg#usage-example)
* [Headless Chrome](https://developer.upsun.com/docs/add-services/headless-chrome#usage-example)
* [InfluxDB](https://developer.upsun.com/docs/add-services/influxdb#usage-example)
* [Kafka](https://developer.upsun.com/docs/add-services/kafka#usage-example)
* [MariaDB/MySQL](https://developer.upsun.com/docs/add-services/mysql#usage-example)
* [Memcached](https://developer.upsun.com/docs/add-services/memcached#usage-example)
* [mercure](https://developer.upsun.com/docs/add-services/mercure#usage-example)
* [mongodb](https://developer.upsun.com/docs/add-services/mongodb#usage-example)
* [Network Storage](https://developer.upsun.com/docs/add-services/network-storage#usage-example)
* [OpenSearch](https://developer.upsun.com/docs/add-services/opensearch#usage-example)
* [PostgreSQL](https://developer.upsun.com/docs/add-services/postgresql#usage-example)
* [RabbitMQ](https://developer.upsun.com/docs/add-services/rabbitmq#usage-example)
* [Redis](https://developer.upsun.com/docs/add-services/redis#usage-example)
* [Solr](https://developer.upsun.com/docs/add-services/solr#usage-example)
* [Valkey](https://developer.upsun.com/docs/add-services/valkey#usage-example)
* [Varnish](https://developer.upsun.com/docs/add-services/varnish#usage-example)
* [Vault KMS](https://developer.upsun.com/docs/add-services/vault#usage-example)
* [Chroma](/tutorials/self-hosted/chroma#3-use-the-relationship-in-your-application)
* [Qdrant](/tutorials/self-hosted/qdrant#4-use-the-relationship-in-your-application)

## PHP settings

You can configure your PHP-FPM runtime configuration by specifying the [runtime in your app configuration](/docs/configure-apps/app-reference/single-runtime-image#runtime).

In addition to changes in runtime, you can also change the PHP settings.
Some commonly used settings are:

| Name                          | Default | Description                                                                                                                                                                                           |
| ----------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max_execution_time`          | `300`   | The maximum execution time, in seconds, for your PHP scripts and apps. A value of `0` means there are no time limits.                                                                                 |
| `max_file_uploads`            | `20`    | The maximum number of files that can be uploaded in each request.                                                                                                                                     |
| `max_input_time`              | `60`    | The maximum time in seconds that your script is allowed to receive input (such as for file uploads). A value of `-1` means there are no time limits.                                                  |
| `max_input_vars`              | `1000`  | The maximum number of input variables that are accepted in each request.                                                                                                                              |
| `memory_limit`                | `128M`  | The memory limit, in megabytes, for PHP. Ensure that the PHP memory limit is set to a lower value than your environment's memory.                                                                     |
| `post_max_size`               | `64M`   | The maximum size, in megabytes, per uploaded file. To upload larger files, increase the value.                                                                                                        |
| `zend.assertions`             | `-1`    | Assertions are optimized and have no impact at runtime. Set assertions to `1` for your local development system. [See more on assertions](https://www.php.net/manual/en/regexp.reference.assertions). |
| `opcache.memory_consumption`  | `64`    | The number of megabytes available for [the OPcache](/docs/languages/php/tuning#opcache-preloading). For large apps with many files, increase this value.                                              |
| `opcache.validate_timestamps` | `On`    | If your app doesn't generate compiled PHP, you can [disable this setting](/docs/languages/php/tuning#disable-opcache-timestamp-validation).                                                           |

### Retrieve the default values

To retrieve the default PHP values, run the following [CLI command](/cli):

```bash theme={null}
upsun ssh "php --info"
```

To get specific default values, use grep.
For example, to get the value for `opcache.memory_consumption`, run the following command:

```bash theme={null}
upsun ssh "php --info" | grep opcache.memory_consumption
```

### Retrieve the settings

To see the settings used on your environment:

1. Find the PHP configuration files with the following [CLI command](/cli):

   ```bash theme={null}
   upsun ssh "php --ini"
   ```

   The output is something like the following:

   ```bash theme={null}
   Configuration File (php.ini) Path: /etc/php/8.0-zts/cli
   Loaded Configuration File:         /etc/php/8.0-zts/cli/php.ini
   Scan for additional .ini files in: /etc/php/8.0-zts/cli/conf.d
   Additional .ini files parsed:      (none)
   ```

2. Display the configuration file by adapting the following command with the output from step 1:

   ```bash theme={null}
   upsun ssh "cat <LOADED_CONFIGURATION_FILE_PATH>"
   ```

### Customize PHP settings

You can customize PHP values for your app in two ways.
The recommended method is to use variables.

<Tabs>
  <Tab title="Using variables">
    Set variables to override PHP settings for a given environment using the [CLI](/cli).

    For example, to set the PHP memory limit to 256 MB on a specific environment, run the following CLI command:

    ```bash theme={null}
    upsun variable:create --level environment \
        --prefix php --name memory_limit \
        --value 256M --environment <ENVIRONMENT_NAME> \
        --no-interaction
    ```

    For more information, see how to use [PHP-specific variables](/docs/development/variables#php-specific-variables).
  </Tab>

  <Tab title="Using `php.ini`">
    You can provide a custom `php.ini` file at the [app root](/docs/configure-apps/app-reference/single-runtime-image#root-directory).
    Using this method isn't recommended since it offers less flexibility and is more error-prone.
    Consider using variables instead.

    For example, to change the PHP memory limit, use the following configuration:

    ```ini php.ini theme={null}
    memory_limit = 256M
    ```
  </Tab>
</Tabs>

If you're using [PHP-CLI](#execution-mode),
you need to take into account the default settings of PHP-CLI when you customize your PHP settings.
The default settings of PHP-CLI can't be overwritten and are the following:

```text theme={null}
max_execution_time=0
max_input_time=-1
memory_limit=-1
```

### Disable functions for security

A common recommendation for securing PHP installations is disabling built-in functions frequently used in remote attacks.
By default, Upsun doesn't disable any functions.

If you're sure a function isn't needed in your app, you can disable it.

For example, to disable `pcntl_exec` and `pcntl_fork`, add the following to your [app configuration](/docs/configure-apps):

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        # The app's name, which must be unique within the project.
        myapp:
          type: 'php:{{version:php:latest}}'
          variables:
            php:
              disable_functions: "pcntl_exec,pcntl_fork"`
  }
</DynamicCodeBlock>

Common functions to disable include:

| Name                                                             | Description                                                                                                                                                                                           |
| ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `create_function`                                                | This function has been replaced by anonymous functions and shouldn't be used anymore.                                                                                                                 |
| `exec`, `passthru`, `shell_exec`, `system`, `proc_open`, `popen` | These functions allow a PHP script to run a bash shell command. Rarely used by web apps except for build scripts that might need them.                                                                |
| `pcntl_*`                                                        | The `pcntl_*` functions are responsible for process management. Most of them cause a fatal error if used within a web request. Cron tasks or workers may need them. Most are usually safe to disable. |
| `curl_exec`, `curl_multi_exec`                                   | These functions allow a PHP script to make arbitrary HTTP requests. If you're using HTTP libraries such as Guzzle, don't disable them.                                                                |
| `show_source`                                                    | This function shows a syntax highlighted version of a named PHP source file. Rarely useful outside of development.                                                                                    |

## Execution mode

PHP has two execution modes you can choose from:

* The command line interface mode (PHP-CLI) is the mode used for command line scripts and standalone apps.
  This is the mode used when you're logged into your container via SSH, for [crons](/docs/configure-apps/image-properties/crons),
  and usually also for [alternate start commands](#alternate-start-commands).
  To use PHP-CLI, run your script with `php <PATH_TO_SCRIPT>`,
  where `<PATH_TO_SCRIPT>` is a file path relative to the [app root](/docs/configure-apps/app-reference/single-runtime-image#root-directory).
* The Common Gateway Interface mode (PHP-CGI) is the mode used for web apps and web requests.
  This is the default mode when the `start` command isn't explicitly set.
  To use PHP-CGI, run your script with a symlink: `/usr/bin/start-php-app <PATH_TO_SCRIPT>`,
  where `<PATH_TO_SCRIPT>` is a file path relative to the [app root](/docs/configure-apps/app-reference/single-runtime-image#root-directory).
  With PHP-CGI, PHP is run using the FastCGI Process Manager (PHP-FPM).

## Alternate start commands

To specify an alternative process to run your code, set a `start` command.
For more information about the start command, see the [web commands reference](/docs/configure-apps/image-properties/web#web-commands).

By default, start commands use PHP-CLI.
Find out how and when to use each [execution mode](#execution-mode).

Note that the `start` command must run in the foreground and is executed before the [deploy hook](/docs/configure-apps/hooks/hooks-comparison).
That means that PHP-FPM can't run simultaneously with another persistent process
such as [ReactPHP](https://github.com/platformsh-examples/platformsh-example-reactphp)
or [Amp](https://github.com/platformsh-examples/platformsh-example-amphp).
If you need multiple processes, they have to run in separate containers.

See some generic examples on how to use alternate start commands:

<Tabs>
  <Tab title="Run a custom script">
    1. Add your script in a PHP file.

    2. Specify an alternative `start` command by adapting the following:

    ```yaml .upsun/config.yaml theme={null}
    applications:
      # The name of the app container. Must be unique within a project.
      myapp:
        # The location of the application's code.
        web:
          commands:
            start: /usr/bin/start-php-app
    ```
  </Tab>

  <Tab title="Run a custom web server">
    1. Add your web server's code in a PHP file.

    2. Specify an alternative `start` command by adapting the following:

    ```yaml .upsun/config.yaml theme={null}
    applications:
      # The name of the app container. Must be unique within a project.
      myapp:
        # The location of the application's code.
        web:
          commands:
            start: /usr/bin/start-php-app
    ```

    3. Configure the container to listen on a TCP socket:

    ```yaml .upsun/config.yaml theme={null}
    applications:
      # The name of the app container. Must be unique within a project.
      myapp:
        # The location of the application's code.
        web:
          upstream:
            socket_family: tcp
            protocol: http
    ```

    When you listen on a TCP socket, the `$PORT` environment variable is automatically set.
    See more options on how to [configure where requests are sent](/docs/configure-apps/image-properties/web#upstream).
    You might have to configure your app to connect via the `$PORT` TCP socket,
    especially when using web servers such as [Swoole](/docs/languages/php/swoole) or [Roadrunner](https://github.com/roadrunner-server/roadrunner).

    4. Optional: Override redirects to let the custom web server handle them:

    ```yaml .upsun/config.yaml theme={null}
    applications:
      # The name of the app container. Must be unique within a project.
      myapp:
        # The location of the application's code.
        locations:
          "/":
            passthru: true
            scripts: false
            allow: false
    ```
  </Tab>

  <Tab title="Run specific tasks">
    To execute runtime-specific tasks (such as clearing cache) before your app starts, follow these steps:

    1. Create a separate shell script that includes all the commands to be run.

    2. Specify an alternative `start` command by adapting the following:

    <DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
      {`
              applications:
                # The name of the app container. Must be unique within a project.
                myapp:
                  # The location of the application's code.
                  web:
                    commands:
                      start: bash <PATH_TO_SCRIPT> && /usr/bin/start-php-app`
          }
    </DynamicCodeBlock>

    `<PATH_TO_SCRIPT>` is the bash script created in step 1.
    `<PATH_TO_SCRIPT>` is a file path relative to the [app root](/docs/configure-apps/app-reference/single-runtime-image#root-directory).
  </Tab>
</Tabs>

## Foreign function interfaces

PHP 7.4 introduced support for [foreign function interfaces (FFIs)](https://en.wikipedia.org/wiki/Foreign_function_interface).
FFIs allow your PHP program to call routines or use services written in C or Rust.

Note: FFIs are only intended for advanced use cases.
Use with caution.

If you are using C code, you need `.so` library files.
Either place these files directly in your repository or compile them in a makefile using `gcc` in your [build hook](/docs/configure-apps/hooks/hooks-comparison#build-hook).
Note: The `.so` library files shouldn't be located in a publicly accessible directory.

If you are compiling Rust code, use the build hook to [install Rust](https://doc.rust-lang.org/stable/book/ch01-01-installation.html).

To leverage FFIs, follow these steps:

1. [Enable and configure OPcache preloading](/docs/languages/php/tuning#enable-opcache-preloading).

2. Enable the FFI extension:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        myapp:
          type: 'php:{{version:php:latest}}'
          runtime:
            extensions:
              - ffi`
  }
</DynamicCodeBlock>

3. Make sure that your [preload script](/docs/languages/php/tuning#opcache-preloading) calls the `FFI::load()` function.
   Using this function in preload is considerably faster than loading the linked library on each request or script run.

4. If you are running FFIs from the command line,
   enable the preloader by adding the following configuration:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        myapp:
          type: 'php:{{version:php:latest}}'
          variables:
            php:
              opcache.enable_cli: true`
  }
</DynamicCodeBlock>

5. Run your script with the following command:

   ```bash theme={null}
   php <CLI_SCRIPT>
   ```

<RepoList lang="php" displayName="PHP" />

## Frameworks

All major PHP web frameworks can be deployed on Upsun.
See dedicated guides for deploying and working with them:

* [Laravel](/docs/get-started/stacks/laravel)
* [Symfony](/docs/get-started/stacks/symfony)

## Modify your PHP runtime when using the composable image

<Warning>
  This section is only relevant when using the Upsun [composable image](/docs/configure-apps/app-reference/composable-image).
</Warning>

The following table presents the possible modifications you can make to your PHP primary runtime using the `stack.runtimes` key in a composable image.

For example, `extensions` are enabled under `.applications.frontend.stack.runtimes[0]["php@8.5"].extensions` for PHP 8.5).
See the [example](#example-php-configuration) below for more details.

<Note>
  The PHP-FPM service starts automatically only when PHP is the primary runtime.
</Note>

| Name                        | Type                                                                                                                                  | Description                                                                                             |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `extensions`                | List of `string`s OR [extensions definitions](/docs/configure-apps/app-reference/composable-image#php-extensions-and-python-packages) | [PHP extensions](/docs/languages/php/extensions) to enable.                                             |
| `disabled_extensions`       | List of `string`s                                                                                                                     | [PHP extensions](/docs/languages/php/extensions) to disable.                                            |
| `request_terminate_timeout` | `integer`                                                                                                                             | The timeout (in seconds) for serving a single request after which the PHP-FPM worker process is killed. |
| `sizing_hints`              | A [sizing hints definition](#php-fpm-service-sizing-hints)                                                                            | The assumptions for setting the number of workers in your PHP-FPM runtime.                              |
| `xdebug`                    | An Xdebug definition                                                                                                                  | The setting to turn on [Xdebug](/docs/languages/php/xdebug).                                            |

### PHP-FPM service sizing hints

The following table shows the properties that can be set in `sizing_hints`:

| Name              | Type      | Default | Minimum | Description                                    |
| ----------------- | --------- | ------- | ------- | ---------------------------------------------- |
| `request_memory`  | `integer` | 45      | 10      | The average memory consumed per request in MB. |
| `reserved_memory` | `integer` | 70      | 70      | The amount of memory reserved in MB.           |

See more about [PHP-FPM workers and sizing](/docs/languages/php/fpm).

### Example PHP configuration

Here is an example configuration:

<DynamicCodeBlock language="yaml" filename=".upsun/config.yaml">
  {`
      applications:
        frontend:
          type: "composable:{{version:composable:latest}}"
          stack:
            runtimes:
              - "php@8.4":
                  extensions:
                    - apcu # A PHP extension made available to the PHP runtime
                    - sodium
                    - xsl
                    - pdo_sqlite

                  xdebug:
                    idekey: YOUR_KEY

                  disabled_extensions:
                    - gd

                  request_terminate_timeout: 200

                  sizing_hints:
                    request_memory: 45
                    reserved_memory: 70

              - "python@3.13"
            packages:
              - "php84Extensions.apcu" # A PHP extension made available to all runtimes.
              - "python313Packages.yq"`
  }
</DynamicCodeBlock>

<Note>
  You can also set your [app's runtime timezone](/docs/configure-apps/timezone).
</Note>
