PHP with Apache
Overview
PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
The HTTP server is Apache 2, and the PHP code is executed by PHP-FPM.
Create an application on Clever Cloud
With the web console
Refer to Quickstart for more details on application creation via the console.
With the Clever Tools CLI
- Make sure you have clever-tools installed locally or follow our CLI getting started guide.
- In your code folder, do
clever create --type <type> <app-name> --region <zone> --org <org>where :typeis the type of technology you rely onapp-namethe name you want for your application,zonedeployment zone (parfor Paris andmtlfor Montreal)orgthe organisation ID the application will be created under.
Refer to clever create for more details on application creation with Clever Tools.
Setting up environment variables on Clever Cloud
With the Clever Cloud console
- Go to the Clever Cloud console, and find the app you want to fine tune under it’s organisation.
- Find the Environment variables menu and select it.
- In this menu, you will see a form with VARIABLE_NAME and variable value fields.
- Fill them with the desired values then select Add.
- Don’t forget to “Update Changes” at the end of the menu.
With the Clever Tools CLI
- Make sure you have clever-tools installed locally. Refer to our CLI getting started.
- In your code folder, do
clever env set <variable-name> <variable-value>
Refer to environment variables reference for more details on available environment variables on Clever Cloud.
You can of course create custom ones with the interface we just demonstrated, they will be available for your application.
Configure your PHP application
Choose your PHP version
Set the CC_PHP_VERSION environment variable to one of the following versions.
| Default Version | Accepted Versions |
|---|---|
8 (8.4) | 5.6 (EOL) |
7 (EOL) | |
7.1 (EOL) | |
7.2 (EOL) | |
7.3 (EOL) | |
7.4 (EOL) | |
8 | |
8.0 (EOL) | |
8.1 | |
8.2 | |
8.3 | |
8.4 |
The end-of-life (EOL) versions are marked as such.
All new PHP applications are created with a default CC_PHP_VERSION. You can of course change it whenever you want then redeploy your application to use the version you want. We only support values based on the first two digits (X or X.Y, not X.Y.Z).
Change the webroot
Since one of the best practices of PHP development is to take the libraries and core files outside the webroot, you may want to set another webroot than the default one (the root of your application).
Using an environment variable
Add a new environment variable called CC_WEBROOT and set /public as its value.
clever env set CC_WEBROOT /publicChange PHP settings
PHP settings
Most PHP settings can be changed using a .user.ini file.
If you want the settings to be applied to the whole application, you should put this file in your webroot. If you did not change it (see above), then your webroot is the root of the repository.
If you put the .user.ini file in a subdirectory; settings will be applied recursively starting from this subdirectory.
Same configuration between PHP-CLI and PHP-FPM.
.user.ini files aren’t loaded by the PHP CLI by default.
However, some PHP applications may want to check for the PHP-FPM configuration pre-requisites, post_max_size or upload_max_filesize values for example.
To load the PHP-FPM .user.ini file during a PHP-CLI process, in a hook, use the PHP_INI_SCAN_DIR environment variable to load the additional file.
Assuming the script runs at the root-folder of the application:
#!/usr/bin/env bash
export PHP_INI_SCAN_DIR=":."
php myscript.phpThis appends the current directory while still loading the default configuration.
Note: The : at the beginning of the string is mandatory. It indicates defaults files must still load.
A specific .ini file can be loaded with:
#!/usr/bin/env bash
export PHP_INI_SCAN_DIR=":.php-configuration/"
php myscript.phpThis loads every .ini files in the php-configuration/ directory.
Timezone configuration
All instances on Clever Cloud run on the UTC timezone. We recommend to handle all your dates in UTC internally, and only handle timezones when reading or displaying dates.
Additionally, you can set PHP’s time zone setting with .user.ini. For instance, to use the french time zone, edit .user.ini to add this line:
date.timezone=Europe/ParisHeader injection
With .htaccess
To inject headers on HTTP responses, add this configuration to .htaccess file:
Header Set Access-Control-Allow-Origin "https://www.example.com"
Header Set Access-Control-Allow-Headers "Authorization".htaccess file to create or update headers, but you can’t delete them.With PHP
You can also do it from PHP:
header("Access-Control-Allow-Origin: https://www.example.com");
header("Access-Control-Allow-Headers: Authorization");If you want to keep this separate from your application, you can configure the application to execute some code on every request.
In .user.ini, add the following line (you need to create inject_headers.php first):
auto_prepend_file=./inject_headers.phpPlease refer to the official documentation for more information.
You can review the available directives; all the PHP_INI_USER, PHP_INI_PERDIR, and PHP_INI_ALL directives can be set from within .user.ini.
Memory Limit
When php-fpm spawns a worker it allocates a smaller part of the application’s memory to the worker, here is the allocated memory for each flavor:
| Flavor | Memory Limit |
|---|---|
| Pico | 64M |
| Nano | 64M |
| XS | 128M |
| S | 256M |
| M | 384M |
| L | 512M |
| XL | 768M |
| 2XL | 1024M |
| 3XL | 1536M |
| 4XL+ | 2048M |
To change this limit you can define MEMORY_LIMIT environment variable.
If you define a limit exceeding the application memory it will use the default one.
Configure Apache
We use Apache 2 as HTTP Server. In order to configure it, you can create a .htaccess file and set directives inside this file.
htaccess
The .htaccess file can be created everywhere in you app, depending of the part of the application covered by directives.
However, directives who applies to the entire application must be declared in a .htaccess file to the application root.
htpasswd
You can configure basic authentication using environment variables. You will need to set CC_HTTP_BASIC_AUTH variable to your own login:password pair. If you need to allow access to multiple users, you can create additional environment CC_HTTP_BASIC_AUTH_n (where n is a number) variables.
Define a custom HTTP timeout
You can define the timeout of an HTTP request in Apache using the HTTP_TIMEOUT environment variable.
By default, the HTTP timeout is set to 3 minutes (180 seconds).
Header size
Default Apache header size is 8k. If you need to increase it, you can set CC_APACHE_HEADERS_SIZE environment variable, between 8 and 256. Effective value depends on deployment region. Ask for a dedicated load balancer for a specific value.
Force HTTPS traffic
Load balancers handle HTTPS traffic ahead of your application. You can use the X-Forwarded-Proto header to know the original protocol (http or https).
Place the following snippet in a .htaccess file to ensure that your visitors only access your application through HTTPS.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]Prevent Apache to redirect HTTPS calls to HTTP when adding a trailing slash
DirectorySlash is enabled by default on the PHP scalers, therefore Apache will add a trailing slash to a resource when it detects that it is a directory.
E.g. if foobar is a directory, Apache will automatically redirect http://example.com/foobar to http://example.com/foobar/.
Unfortunately the module is unable to detect if the request comes from a secure connection or not. As a result it will force an HTTPS call to be redirected to HTTP.
In order to prevent this behavior, you can add the following statements in a .htaccess file:
DirectorySlash Off
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ %{HTTP:X-Forwarded-Proto}://%{HTTP_HOST}/$1/ [R=301,L,QSA]These statements will keep the former protocol of the request when issuing the redirect. Assuming that the header X-Forwarded-Proto is always filled (which is the case on our platform).
If you want to force all redirects to HTTPS, you can replace %{HTTP:X-Forwarded-Proto} with https.
Change the FastCGI module
You can choose between two FastCGI modules, fastcgi and proxy_fcgi, using the CC_CGI_IMPLEMENTATION environment variable. If you don’t set it proxy_fcgi is used as default value. We recommend it, as fastcgi implementation is not maintained anymore.
If you have issues with downloading content, it could be related to the fastcgi module not working correctly in combination with the deflate module, as the Content-Length header is not updated to the new size of the encoded content. To resolve this issue, use proxy_fcgi.
Environment injection
As mentioned above, Clever Cloud can inject environment variables that are defined in the dashboard and by add-ons linked to your application.
To access the variables, use the getenv function. So, for example, if
your application has a postgresql add-on linked:
$host = getenv("POSTGRESQL_ADDON_HOST");
$database = getenv("POSTGRESQL_ADDON_DB");
$username = getenv("POSTGRESQL_ADDON_USER");
$password = getenv("POSTGRESQL_ADDON_PASSWORD");
$pg = new PDO("postgresql:host={$host};dbname={$database}, $username, $password);
phpinfo(). If you want to use phpinfo() without exposing environment variables, you have to call it this way: phpinfo(INFO_GENERAL | INFO_CREDITS | INFO_CONFIGURATION | INFO_MODULES | INFO_LICENSE)Composer
We support Composer build out of the box. You just need to provide a composer.json file in the root of your repository and we will run composer.phar install --no-ansi --no-progress --no-interaction --no-dev for you.
You can also set the CC_COMPOSER_VERSION to 1 or 2 to select the composer version to use.
composer.phar file in the root of your repository which will override the version we use.You can perform your own composer.phar install by using the Post Build hook.
Example of a composer.json file:
| |
Example of a minimalist PHP application using composer and custom scripts: php-composer-demo
Development Dependencies
Development dependencies will not be automatically installed during the deployment. You can control their installation by using the CC_PHP_DEV_DEPENDENCIES environment variable which takes install value.
Any other value than install will prevent development dependencies from being installed.
GitHub rate limit
Sometimes, you can encounter the following error when downloading dependencies:
Failed to download symfony/symfony from dist: Could not authenticate against GitHub.comTo prevent this download dependencies’s fails that is often caused by rate limit of GitHub API while deploying your apps,
we recommend you to add oauth token in your composer configuration file or in separate file named as described in
composer FAQ (API rate limit and OAuth tokens).
You can find more documentation about composer configuration at getcomposer.com.
Example
You use Artisan to manage your project and you want to execute artisan migrate before running your app.
To do this, we use a post build hook, you have to set a new environment variable on your Clever application as following:
CC_POST_BUILD_HOOK=php artisan migrate --forceNote: You must add the execute permission to your file (chmod u+x yourfile) before pushing it.
Frameworks and CMS
The following is the list of tested CMS by our team.
It’s quite not exhaustive, so it does not mean that other CMS can’t work on the Clever Cloud platform.
Others PHP frameworks tested on Clever Cloud:
- Prestashop
- Dokuwiki
- Joomla
- SugarCRM
- Drupal
- Magento
- Status.net
- Symfony
- Thelia
- Laravel
- Sylius
Available extensions and modules
Clever Cloud PHP with Apache applications enable the following extensions by default:
amqp, bcmath, bz2, calendar, ctype, curl, dba, exif, fileinfo, filter, ftp, gd, gettext, gmp, iconv, imagick, imap, intl, json, ldap, libsodium, mbstring, mcrypt, memcached, memcache, mongodb, mysql, mysqli, opcache, pcntl, pcre, pdo-mysql, pdo-odbc, pdo-pgsql, pdo-sqlite, pgsql, phar, posix, pspell, readline, redis, session, shmop, sockets, sodium, solr, ssh2, ssl, tidy, tokenizer, unixodbc, xml, xmlrpc, xsl, zip, zlib.
You can also enable the following extensions on demand:
apcu, blackfire, elastic_apm_agent, event, excimer, geos, gnupg, grpc, ioncube, imap, mailparse, maxminddb, mongo, newrelic, oauth, opentelemetry, pcs, PDFlib, pdo_sqlsrv, protobuf, pspell, rdkafka, scoutapm, sqlsrv, sqreen, tideways, uopz, uploadprogress, xdebug, xmlrpc, yaml
Note
Only some extensions support PHP 8.4 for now: amqp, apcu, blackfire, event, gnupg, grpc, imagick, imap, mailparse, maxminddb, memcache, memcached, mongodb, newrelic, oauth, opentelemetry, pdo_sqlsrv, protobuf, pspell, rdkafka, redis, solr, sqlsrv, ssh2, tideways, uploadprogress, yaml, zip. We’ll add support for more extensions as they are released.
You can check extensions and versions by viewing our phpinfo() for:
If you have a request about extensions, contact Clever Cloud Support.
Enable specific extensions
Some extensions need to be enabled explicitly. To do so, set the corresponding environment variable:
APCu: set
ENABLE_APCUtotrue.APCu is an in-memory key-value store for PHP. Keys are of type string and values can be any PHP variables.
Elastic APM Agent: set
ENABLE_ELASTIC_APM_AGENTtotrue(default ifELASTIC_APM_SERVER_URLis defined).Elastic APM agent is Elastic’s APM agent extension for PHP. The PHP agent enables you to trace the execution of operations in your application, sending performance metrics and errors to the Elastic APM server. Warning: This extension is available starting PHP 7.2.
Event: set
ENABLE_EVENTtotrue.Event is an extension to schedule I/O, time and signal based events.
Excimer: set
ENABLE_EXCIMERtotrue.Excimer is an extension that provides a low-overhead interrupting timer and sampling profiler.
GEOS: set
ENABLE_GEOStotrue.GEOS (Geometry Engine - Open Source) is a C++ port of the Java Topology Suite (JTS).
GnuPG: set
ENABLE_GNUPGtotrue.GnuPG is an extension that provides methods to interact with GNU Privacy Guard (OpenPGP implementation).
gRPC: set
ENABLE_GRPCtotrue.gRPC is an extension for the high performance, open source, general RPC framework layered over HTTP/2.
IonCube: set
ENABLE_IONCUBEtotrue.IonCube is a tool to obfuscate PHP code. It’s often used by paying Prestashop and WordPress plugins.
IMAP (only for PHP 8.4+): set
ENABLE_IMAPtotrue.IMAP is an extension to operate with the IMAP protocol, as well as the NNTP, POP3, and local mailbox access methods.
Mailparse: set
ENABLE_MAILPARSEtotrue.Mailparse is an extension for parsing and working with email messages. It can deal with RFC 822 and RFC 2045 (MIME) compliant messages.
MaxMind DB: set
ENABLE_MAXMINDDBtotrue.Extension for reading MaxMind DB files. MaxMind DB is a binary file format that stores data indexed by IP address subnets (IPv4 or IPv6).
Mongo: set
ENABLE_MONGOtotrue.MongoDB is a NoSQL Database. This extension allows to use it from PHP. Warning: this extension is now superseded by the
mongodbextension. We provide it for backward compatibility.NewRelic: set
ENABLE_NEWRELICtotrue.Newrelic Agent for PHP. Newrelic is a software analytics tool.
OAuth: set
ENABLE_OAUTHtotrue.OAuth consumer extension. OAuth is an authorization protocol built on top of HTTP.
OpenTelemetry: set
ENABLE_OPENTELEMETRYtotrue.OpenTelemetry is an extension to facilitate the generation, export, collection of telemetry data such as traces, metrics, and logs.
PCS: set
ENABLE_PCStotrue.PCS provides a fast and easy way to mix C and PHP code in your PHP extension.
PDFlib: set
ENABLE_PDFlibtotrue.PDFlib is a commercial library for generating PDF files. It provides a PHP extension to create and manipulate PDF documents.
Protobuf: set
ENABLE_PROTOBUFtotrue.Protobuf is an extension for the language-neutral, platform-neutral extensible mechanism for serializing structured data.
Pspell: set
ENABLE_PSPELLtotrue.Pspell is an extension to check the spelling of words and offer suggestions.
Rdkafka: set
ENABLE_RDKAFKAtotrue.PHP-rdkafka is a thin librdkafka binding providing a working PHP 5 / PHP 7 Kafka client.
Scout APM: set
ENABLE_SCOUTAPMtotrue.The Scout APM extension to provide additional capabilities to application monitoring over just using the base PHP userland library.
SQL Server: set
ENABLE_SQLSRVorENABLE_PDO_SQLSRVtotrue.These extensions enable drivers that rely on the Microsoft ODBC Driver to handle the low-level communication with SQL Server. The
SQLSRVextension provides a procedural interface while thePDO_SQLSRVextension implements PDO for accessing data in all editions of SQL Server 2012 and later (including Azure SQL DB).Sqreen: The Sqreen agent is started automatically after adding the environment variables (
SQREEN_API_APP_NAMEandSQREEN_API_TOKEN).Tideways: set
ENABLE_TIDEWAYStotrue.Tideways is an extension that provides profiling and monitoring capabilities for PHP applications.
Uopz: set
ENABLE_UOPZtotrue.The uopz extension is focused on providing utilities to aid with unit testing PHP code.
Uploadprogress: set
ENABLE_UPLOADPROGRESStotrue.The uploadprogress extension is used to track the progress of a file download.
XDebug: set
ENABLE_XDEBUGtotrue.XDebug is a debugger and profiler tool for PHP.
XML RPC: set
ENABLE_XMLRPCtotrue.XML-RPC is an extension for server and client bindings
YAML: set
ENABLE_YAMLtotrue.YAML is an extension providing a YAML-1.1 parser and emitter
You can use DISABLE_<extension_name>=true in your environment variables to disable an extension.
Configure the session storage
By default, an FS Bucket is created for each PHP applications, so that session data is available on each instance. This FS Bucket is also used to store TMP files by default. You can change this behavior by setting the TMPDIR environment variable. You can set it to /tmp for example.
FS Buckets are not available in HDS regions
To deploy a PHP application on an HDS region, set CC_PHP_DISABLE_APP_BUCKET=true. Consider using Redis to manage PHP sessions.
Speed up or disable the session FS Bucket
You can set the following environment variables:
CC_PHP_ASYNC_APP_BUCKET=asyncto mount the session FS Bucket with theasyncoption. It speeds up the FS Bucket usage, but it can corrupt files in case of a network outage.CC_PHP_DISABLE_APP_BUCKET=(true|yes|disable)to entirely prevent the session FS Bucket from being mounted. Use this if you don’t use the default PHP session library. It will speed up your application but users might lose their session across instances and deployments.
Use Redis to store PHP Sessions
We provide the possibility to store the PHP sessions in a Redis database to improve reliability.
If your application is under heavy load, redis persistence for sessions can improve latency.
To enable this feature, you need to:
- enable Redis support on the application (create an environment variable named
ENABLE_REDISwith the valuetrue.) - create and link a Redis add-on
- create an environment variable named
SESSION_TYPEwith the valueredis.
Sending emails
The PHP language has the mail function to directly send emails. While we do not provide a SMTP server (needed to send the emails), you can configure one through environment variables.
We provide Mailpace add-on to send emails through PHP mail() function. You have to turn TLS on with port 465 (environment variable CC_MTA_SERVER_USE_TLS=true) to make Mailpace working.
We also recommend you to use Mailgun or Mailjet if your project supports it. These services already have everything you need to send emails from your code.
Configure the SMTP server
Services like Mailgun or Mailjet provide SMTP servers. If your application has no other way but to use the mail function of PHP to send emails, you have to configure a SMTP server. This can be done through environment variables:
CC_MTA_SERVER_HOST: Host of the SMTP server.CC_MTA_SERVER_PORT: Port of the SMTP server. Defaults to465whether TLS is enabled or not.CC_MTA_AUTH_USER: User to authenticate to the SMTP server.CC_MTA_AUTH_PASSWORD: Password to authenticate to the SMTP server.CC_MTA_SERVER_USE_TLS: Enable or disable TLS. Defaults totrue.CC_MTA_SERVER_STARTTLS: Enable or disable STARTTLS. Defaults tofalse.CC_MTA_SERVER_AUTH_METHOD: Enable or disable authentication. Defaults toon.
Configure Monolog
A lot of frameworks (including Symfony) use Monolog to handle logging. The default configuration of Monolog doesn’t allow to log errors into the console.
Here is a basic configuration of Monolog to send your application’s logs into our logging system and access them into the Console:
monolog:
handlers:
clever_logs:
type: error_log
level: warningYou can change the level to whatever level you desire. For Symfony, the configuration file is app/config/config_prod.yml.
Laravel doesn’t need Monolog to retrieve logs via Clever console or Clever CLI. Here, ensure that you have the following line in config/app.php:
return [
// …
'log' => env('APP_LOG'),
// …
];Then, set APP_LOG=syslog as Clever application environment variable.
Using HTTP authentication
Using basic HTTP authentication, PHP usually handles the values of user and password in variables named $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'].
At Clever Cloud, we have enabled an Apache option to pass directly the Authorization header, even though we are using FastCGI; still, the header is not used by PHP, and the aforementioned variables are empty.
You can do this to fill them using the Authorization header:
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':' , base64_decode(substr($_SERVER['Authorization'], 6)));Monitor your application with New Relic
You can use New Relic to monitor your application on Clever Cloud.
Please refer to our New Relic documentation to configure it for your application.
Monitor your application with Blackfire
You can use Blackfire to monitor your application on Clever Cloud.
Please refer to our Blackfire documentation to configure it for your application.
Deploy on Clever Cloud
Application deployment on Clever Cloud is via Git or FTP.
Git Deployment on Clever Cloud
You need Git on your computer to deploy via this tool. Here is the official website of Git to get more information: git-scm.com
Setting up your remotes
The “Information” page of your app gives you your Git deployment URL, it looks like this:
git+ssh://git@push.clever-cloud.com/<your_app_id>.git- Copy it in your clipboard
Locally, under your code folder, type in
git initto set up a new git repository or skip this step if you already have oneAdd the deploy URL with
git remote add <name> <your-git-deployment-url>Add your files via
git add <files path>and commit them viagit commit -m <your commit message>Now push your application on Clever Cloud with
git push <name> master
Refer to git deployments for more details.
FTP Deployment
Make sure you have Filezilla or an other FTP software installed in your machine.
When you chose to deploy your application via FTP at the application creation, the system creates a free FS Bucket with an ID matching your application’s ID.
Find the FTP credentials in the configuration tab of this particular FS Bucket.
Just follow the instructions of your FTP Software to send code to Clever Cloud.
⚠️ An FTP application automatically starts once you create the application, even if you don’t send any code yet.
Refer to Quick Start - FTP deployment for more details.
ProxySQL
ProxySQL is a tool that acts like a proxy between your application and your MySQL add-on. Instead of connecting to your MySQL add-on, you can connect to the local ProxySQL and it will forward all your requests to your MySQL add-on.
This allows you to let ProxySQL take care of some interesting features like connection pooling or leader / follower setup.
You can learn more about ProxySQL on the dedicated documentation page
More configuration
Need more configuration? To run a script at the end of your deployment? To add your private SSH key to access private dependencies?
Go check the Common configuration page.
You may want to have an advanced usage of your application, in which case we recommend you to read the Administrate documentation section.
If you can’t find something or have a specific need like using a non supported version of a particular software, please reach out to the support.
Enable health check during deployment
The healthcheck allows you to limit downtimes. Indeed, you can provide Clever Cloud with paths to check. If these paths return something other than 200, the deployment will fail.
Add one (or several) environment variable as such:
CC_HEALTH_CHECK_PATH=/my/awesome/pathOr
CC_HEALTH_CHECK_PATH_0=/my/awesome/path
CC_HEALTH_CHECK_PATH_1=/my/other/pathThe deployment process checks all paths. All of them must reply with a 200 OK response code.
By default, when no environment variable (for ex: APP_HOME) is defined, the monitoring checks your repository root path /.
Example
Using the path listed above, below are the expected logs:
Response from GET /my/awesome/path is 200
Response from GET /my/other/path is 500
Health check failed:
- GET /my/other/path returned 500.
If the deployment fails after this message, please update your configuration and redeploy.In this example, the first path is OK, but the second one failed. This gives you a hint on what failed in your application.
Best practice for healthcheck endpoints
To make the most of a healthcheck endpoint, have it check your critical dependencies. For example:
- execute
SELECT 1 + 1;on your database - retrieve a specific Cellar file
- ping a specific IP through a VPN
Did this documentation help you ?