On this page

PHP

Create a Clever Cloud account

The API of Clever Cloud uses OAuth 1 to perform authentication actions. There are two ways to signup to Clever Cloud: email or GitHub login.

Go to the Clever Cloud Console and select the method you prefer.

Email Authentication

This kind of auth requires a valid and non-temporary disposable e-mail, and a password having at least 6 characters. Do not forget to validate your email by clicking the link you will receive.

GitHub Authentication

The GitHub signup allows you to create an account or link your existing one to GitHub, in one click. This process asks the following permissions: 

  • Read your Public Key
  • Read User Repositories

The “repository permission” is used to deploy your GitHub apps directly to Clever Cloud, with a simple step.

If you need to give access to Clever Cloud’s API to a specific GitHub organization, you can do it here.

Two Factor Authentication (2FA)

Clever Cloud supports 2FA. You can enable it here: https://console.clever-cloud.com/users/me/authentication

Please, backup your recovery codes, we won’t be able to restore access to your account if you lose access to your regular codes.

You need to add a SSH key to your Clever Cloud’s account to deploy via Git. SSH keys are used to establish a secure connection between your computer and Clever Cloud. A user can have multiple SSH keys.

I need to create my SSH key

  1. In your Terminal, enter the following bash line:

    ssh-keygen -t ed25519 -C "your_email@youremail.com"
    

    This command creates a new ssh key using the provided email, so that the owner of the key can be identified.

  2. When prompted in which file you want to save the key, just press enter. If it says that the file already exists, enter n for no. Type ls, verify the presence of the file and jump to Add your SSH key on Clever Cloud.

  3. When asked, enter a passphrase:

Generating public/private ed25519 key pair.
Enter file in which to save the key (/your_home_path/.ssh/id_ed25519):
# Now you should enter a passphrase.
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

Which should give you something like this:

Your identification has been saved in /your_home_path/.ssh/id_ed25519.
Your public key has been saved in /your_home_path/.ssh/id_ed25519.pub.
The key fingerprint is:
01:0e:e5:2d:ab:98:d6:17:a1:6d:f0:68:9f:d0:a2:db your_email@youremail.com

I created my account with GitHub

If your account is linked to GitHub, a panel with your GitHub SSH keys will appear in the “SSH Keys” tab. You can add any key already present in your GitHub account by clicking on the import button next to it.

Add your SSH key on Clever Cloud

Public SSH Key

To declare your public SSH Key on Clever Cloud, in the left navigation bar, go in “Profile” and in the “SSH Keys” tab, add the key by entering a name and the public SSH key. The key is the entire content of the **id_[ed25519/rsa].pub** file including the id_ed25519/ssh-rsa part and your email.

Private SSH Key

If you want to clone a repository from a private repository, you can add a Private SSH Key to an application by creating a folder clevercloud at the root of your application and creating the file clevercloud/ssh.json with the following content:

{
    "privateKeyFile": "path/to/file"
}

Of course you need to provide a valid path to a file that contains a valid key and that you will push on the Clever Cloud git remote.

If you have trouble configuring this key you can refer to this extended documentation

Create an application on Clever Cloud

via the web console

  1. Create a new app by clicking on the Add an Application button, in the sidebar.
  2. Select a brand new instance (or a repository from GitHub if your account is linked).
  3. Then select PHP in the platform list.
  4. Configure your scaling options.
  5. Enter your application’s name and description and click “Next”. You can also select the region you want (North America or Europe).

Refer to the getting started for more details on application creation via the console.

via the Clever Tools CLI

  1. Make sure you have clever-tools installed locally. Report to the getting started.
  2. In your code folder, do clever create --type <type> <app-name> --region <zone> --org <org> where type is the type of technology you rely on, app-name the name you want for your application, zone deployment zone (par for Paris and mtl for Montreal), and org the organization ID the application will be created under.

Refer to the documentation for more details on application creation with Clever Tools.

Setting up environment variables on Clever Cloud

With the Clever Cloud console

  1. Go to the Clever Cloud console, and find the app you want to fine tune under it’s organization.
  2. Find the Environment variables menu and select it.
  3. In this menu, you will see a form with VARIABLE_NAME and variable value fields. Fill them with the desired values then select Create.

With the Clever Tools CLI

  1. Make sure you have clever-tools installed locally. Report to the getting started
  2. 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 values:

  • 5.6
  • 7.2
  • 7.3
  • 7.4
  • 8.0

All new PHP applications are created with a default CC_PHP_VERSION, set to 7, which means latest php 7 version available.

You can of course change it whenever you want then redeploy your application to use the version you want.

The configuration file for your PHP application must be /clevercloud/php.json, that is a php.json file in a /clevercloud folder at the root of your application.

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 /public

Using a configuration file

To change the webroot, just set the key webroot in the deploy part of the configuration file clevercloud/php.json with the absolute path (from the root of your application) of your new public folder.

In the following example we want to set the webroot to the folder /public:

{
    "deploy": {
        "webroot": "/public"
    }
}

Change 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 sub-directory; settings will be applied recursively starting from this sub-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/Paris
Header injection

Usually, you can use an .htaccess file to create / update / delete headers. You won’t be able to do it from the .htaccess file if the headers come from a .php file, because php-fpm ignores the mod_headers plugin. It works fine for static files directly served by apache.

So if you need to inject headers on HTTP responses (for instance for CORS), you have to do it from PHP (you can’t do it from .htaccess).

header("Access-Control-Allow-Origin: *");

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

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

Note: .user.ini files are not loaded by the php cli

clevercloud/php.json settings

Other settings than the one mentioned above can be changed by adding the following line in clevercloud/php.json:

{
    "configuration": {
        "my.setting": "value"
    }
}

Here is the list of available settings:

  • mbstring.func_overload
  • pm.max_children

Note: You can send a request to the support if you need to change a setting which cannot be changed via a .user.ini file and is not in this list.

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:

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.

pm.max_children: Maximum PHP Children per instance

You can fix the maximum number of PHP running processes per instance by setting pm.max_children (see above).

This setting is useful if you need to limit the number of running processes according to the maximum connections limit of your MySQL or PostgreSQL database.

By default, pm.max_children is set to 10.

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

If you need basic authentication, you can use the .htpasswd file. The path to the .htpasswd of the AuthUserFile directive has to be absolute. Your site root folder is available at /var/www/bas/site/, so the directive should look like: AuthUserFile /var/www/bas/site/.htpasswd

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 se to 3 minutes (180 seconds).

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.

eg. 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 issuying 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.

To choose between these two modules you must use the CC_CGI_IMPLEMENTATION environment variable with fastcgi or proxy_fcgi as a value.

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, we advise you to switch the value of CC_CGI_IMPLEMENTATION from default to proxy_fcgi.

Environment injection

As mentionned 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:

<?php

$dbh = new PDO( 'postgresql:host='.getenv("POSTGRESQL_ADDON_HOST").';dbname='.getenv("POSTGRESQL_ADDON_DB"), getenv("POSTGRESQL_ADDON_USER"), getenv("POSTGRESQL_ADDON_PASSWORD") );

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.

You can perform your own composer.phar install by using the Post Build hook.

Example of a composer.json file:

{
    "require": {
        "laravel/framework": "4.1.*",
        "ruflin/Elastica": "dev-master",
        "shift31/laravel-elasticsearch": "dev-master",
        "natxet/CssMin": "dev-master"
    },
    "repositories": [
        {
            "type": "vcs",
            "url": "https://GitHub.com/timothylhuillier/laravel-elasticsearch.git"
        }
    ],
    "autoload": {
        "classmap": [
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds"
        ],
        "psr-0": {
            "SomeApp": "app"
        }
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev"
}

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 developement 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.com

To 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 --force

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

WordPressPrestashop
DokuwikiJoomla
SugarCRMDrupal
MagentoStatus.net
SymfonyThelia
Laravel-

Available extensions and modules

You can check enabled extensions and versions by viewing our phpinfo() example for

Warning: some extensions need to be enabled explicitely

The following extensions are enabled by default: amqp, imagick, libsodium, memcached, memcache, mongodb, opcache, redis, solr, ssh2, zip.

You can add DISABLE_<extension_name>: true in your environment variable to disable them.

If you have a request about modules, feel free to contact our support at support@clever-cloud.com.

Enable specific extensions

Some extensions need to be enabled explicitly. To enable these extensions, you’ll need to set the corresponding environment variable:

  • APC: set ENABLE_APC to true.

    APC is a framework for caching and optimizing PHP intermediate code. Warning: APC is only available for PHP 5.4.

  • APCu: set ENABLE_APCU to true.

    APCu is an in-memory key-value store for PHP. Keys are of type string and values can be any PHP variables.

  • Couchbase: set ENABLE_COUCHBASE and ENABLE_PCS to true

    Couchbase is a document database with a SQL-based query language that is engineered to deliver performance at scale.

  • Elastic APM Agent: set ENABLE_ELASTIC_APM_AGENT to true (default if ELASTIC_APM_SERVER_URL is 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.

  • IonCube: set ENABLE_IONCUBE to true.

    IonCube is a tool to obfuscate PHP code. It’s often used by paying Prestashop and WordPress plugins.

  • Mailparse: set ENABLE_MAILPARSE to true.

    Mailparse is an extension for parsing and working with email messages. It can deal with RFC 822 and RFC 2045 (MIME) compliant messages.

  • Mongo: set ENABLE_MONGO to true.

    MongoDB is a NoSQL Database. This extension allows to use it from PHP. Warning: this extension is now superseded by the mongodb extension. We provide it for backward compatibility.

  • NewRelic: set ENABLE_NEWRELIC to true.

    Newrelic Agent for PHP. Newrelic is a software analytics tool.

  • OAuth: set ENABLE_OAUTH to true.

    OAuth consumer extension. OAuth is an authorization protocol built on top of HTTP.

  • XDebug: set ENABLE_XDEBUG to true.

    XDebug is a debugger and profiler tool for PHP.

  • Rdkafka: set ENABLE_RDKAFKA to true.

    PHP-rdkafka is a thin librdkafka binding providing a working PHP 5 / PHP 7 Kafka client.

  • Sqreen: The Sqreen agent is started automatically after adding the environment variables (SQREEN_API_APP_NAME and SQREEN_API_TOKEN).

Use Redis to store PHP Sessions

By default, sessions are stored on a replicated file system, so that session data is available on each instance. We also provide the possibility to store the PHP sessions in a Redis database to improve performance: 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_REDIS with the value true.)
  • create and link a Redis add-on
  • create an environment variable named SESSION_TYPE with the value redis.

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 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 to 465 whether 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 (no STARTTLS support). Defaults to true.
  • CC_MTA_SERVER_AUTH_METHOD: Enable or disable authentication. Defaults to on.

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:    warning

You 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:

...
'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)));

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

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

  2. Locally, under your code folder, type in git init to set up a new git repository or skip this step if you already have one.

  3. Add the deploy URL with git remote add <name> <your-git-deployment-url>.

  4. Add your files via git add <files path> and commit them via git commit -m <your commit message>.

  5. Now push your application on Clever Cloud with git push <name> master

Refer to the quickstart for more details on git deployments.

Linking a database or any other add-on to your application

By linking an application to an add-on, the application has the add-on environment variables in its own environment by default.

On add-on creation

Many add-ons do exist on Clever Cloud, please refer to the full list and check add-ons dedicated pages for full instructions.

During add-on creation, you will see Applications screen, with a list of your applications. You can toggle the button to Link and click next. If you finish the process of add-on creation, the application will automatically be linked to it.

Add-on already exists

In the Clever Cloud console, under the Service Dependencies menu of your application, you can use the Link addons dropdown menu to select the name of the add-on you want to link and use the add button to finish the process.

You can also link another application from the same page in the Clever Cloud console, using the Link applications dropdown menu.

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.

Comments