Table of Contents
- annotations
- assets
- cache
- csrf_protection
- default_locale
- disallow_search_engine_index
- error_controller
- esi
- exceptions
- form
- fragments
- handle_all_throwables
- html_sanitizer
- http_cache
- http_client
- http_method_override
- ide
- lock
- mailer
- messenger
- php_errors
- profiler
- property_access
- property_info
- rate_limiter
- request
- router
- secret
- secrets
- semaphore
- serializer
- session
- ssi
- test
- translator
- trust_x_sendfile_type_header
- trusted_headers
- trusted_hosts
- trusted_proxies
- validation
- web_link
- webhook
- workflows
Framework Configuration Reference (FrameworkBundle)
The FrameworkBundle defines the main framework configuration, from sessions andtranslations to forms, validation, routing and more. All these options areconfigured under theframework key in your application configuration.
12345
# displays the default config values defined by Symfony$php bin/console config:dump-reference framework# displays the actual config values used by your application$php bin/console debug:config frameworkNote
When using XML, you must use thehttp://symfony.com/schema/dic/symfonynamespace and the related XSD schema is available at:https://symfony.com/schema/dic/symfony/symfony-1.0.xsd
annotations
cache
type:stringdefault:php_array
This option can be one of the following values:
- php_array
- Use a PHP array to cache annotations in memory
- file
- Use the filesystem to cache annotations
- none
- Disable the caching of annotations
debug
type:booleandefault:%kernel.debug%
Whether to enable debug mode for caching. If enabled, the cache willautomatically update when the original file is changed (both with code andannotation changes). For performance reasons, it is recommended to disabledebug mode in production, which will happen automatically if you use thedefault value.
file_cache_dir
type:stringdefault:%kernel.cache_dir%/annotations
The directory to store cache files for annotations, in caseannotations.cache is set to'file'.
assets
The following options configure the behavior of theTwig asset() function.
base_path
type:string
This option allows you to prepend a base path to the URLs generated for assets:
12345
# config/packages/framework.yamlframework:# ...assets:base_path:'/images'12345678910111213
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:assetsbase-path="/images"/></framework:config></container>12345678
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{// ...$framework->assets() ->basePath('/images');};With this configuration, a call toasset('logo.png') will generate/images/logo.png instead of/logo.png.
base_urls
type:array
This option allows you to define base URLs to be used for assets.If multiple base URLs are provided, Symfony will select one from thecollection each time it generates an asset's path:
123456
# config/packages/framework.yamlframework:# ...assets:base_urls:-'http://cdn.example.com/'12345678910111213
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:assetsbase-url="http://cdn.example.com/"/></framework:config></container>12345678
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{// ...$framework->assets() ->baseUrls(['http://cdn.example.com/']);};json_manifest_path
type:stringdefault:null
The file path or absolute URL to amanifest.json file containing anassociative array of asset names and their respective compiled names. A commoncache-busting technique using a "manifest" file works by writing out assets witha "hash" appended to their file names (e.g.main.ae433f1cb.css) during afront-end compilation routine.
Tip
Symfony'sWebpack Encore supportsoutputting hashed assets. Moreover, thiscan be incorporated into many other workflows, including Webpack andGulp usingwebpack-manifest-plugin andgulp-rev, respectively.
This option can be set globally for all assets and individually for each assetpackage:
12345678910111213141516
# config/packages/framework.yamlframework:assets:# this manifest is applied to every asset (including packages)json_manifest_path:"%kernel.project_dir%/public/build/manifest.json"# you can use absolute URLs too and Symfony will download them automatically# json_manifest_path: 'https://cdn.example.com/manifest.json'packages:foo_package:# this package uses its own manifest (the default file is ignored)json_manifest_path:"%kernel.project_dir%/public/build/a_different_manifest.json"# Throws an exception when an asset is not found in the manifeststrict_mode:%kernel.debug%bar_package:# this package uses the global manifest (the default file is used)base_path:'/images'12345678910111213141516171819202122232425
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><!-- this manifest is applied to every asset (including packages) --><framework:assetsjson-manifest-path="%kernel.project_dir%/public/build/manifest.json"><!-- you can use absolute URLs too and Symfony will download them automatically --><!-- <framework:assets json-manifest-path="https://cdn.example.com/manifest.json"> --><!-- this package uses its own manifest (the default file is ignored) --><!-- Throws an exception when an asset is not found in the manifest --><framework:packagename="foo_package"json-manifest-path="%kernel.project_dir%/public/build/a_different_manifest.json"strict-mode="%kernel.debug%"/><!-- this package uses the global manifest (the default file is used) --><framework:packagename="bar_package"base-path="/images"/></framework:assets></framework:config></container>123456789101112131415161718192021
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{// ...$framework->assets()// this manifest is applied to every asset (including packages) ->jsonManifestPath('%kernel.project_dir%/public/build/manifest.json');// you can use absolute URLs too and Symfony will download them automatically// 'json_manifest_path' => 'https://cdn.example.com/manifest.json',$framework->assets()->package('foo_package')// this package uses its own manifest (the default file is ignored) ->jsonManifestPath('%kernel.project_dir%/public/build/a_different_manifest.json')// Throws an exception when an asset is not found in the manifest ->setStrictMode('%kernel.debug%');$framework->assets()->package('bar_package')// this package uses the global manifest (the default file is used) ->basePath('/images');};Note
This parameter cannot be set at the same time asversion orversion_strategy.Additionally, this option cannot be nullified at the package scope if a global manifestfile is specified.
Tip
If you request an asset that isnot found in themanifest.json file, the original -unmodified - asset path will be returned.You can setstrict_mode totrue to get an exception when an asset isnot found.
Note
If a URL is set, the JSON manifest is downloaded on each request using thehttp_client.
After having configured one or more asset packages, you have two ways of injectingthem in any service or controller:
(1) Use a specific argument name
Type-hint your constructor/method argument withPackageInterface and namethe argument using this pattern: "asset package name in camelCase". For example,to inject thefoo_package package defined earlier:
12345678910
useSymfony\Component\Asset\PackageInterface;classSomeService{publicfunction__construct(private PackageInterface$fooPackage ):void{// ... }}(2) Use the#[Target] attribute
Whendealing with multiple implementations of the same typethe#[Target] attribute helps you select which one to inject. Symfony createsa target called "asset package name" +.package suffix.
For example, to select thefoo_package package defined earlier:
1234567891011
// ...useSymfony\Component\DependencyInjection\Attribute\Target;classSomeService{publicfunction__construct(#[Target('foo_package.package')]private PackageInterface$package ):void{// ... }}packages
You can group assets into packages, to specify different base URLs for them:
1234567
# config/packages/framework.yamlframework:# ...assets:packages:avatars:base_urls:'http://static_cdn.example.com/avatars'1234567891011121314151617
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:assets><framework:packagename="avatars"base-url="http://static_cdn.example.com/avatars"/></framework:assets></framework:config></container>123456789
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{// ...$framework->assets() ->package('avatars') ->baseUrls(['http://static_cdn.example.com/avatars']);};Now you can use theavatars package in your templates:
1
<imgsrc="{{ asset('...', 'avatars') }}">Each package can configure the following options:
strict_mode
type:booleandefault:false
When enabled, the strict mode asserts that all requested assets are in themanifest file. This option is useful to detect typos or missing assets, therecommended value is%kernel.debug%.
version
type:string
This option is used tobust the cache on assets by globally adding a queryparameter to all rendered asset paths (e.g./images/logo.png?v2). Thisapplies only to assets rendered via the Twigasset() function (or PHPequivalent).
For example, suppose you have the following:
1
<imgsrc="{{ asset('images/logo.png') }}"alt="Symfony!"/>By default, this will render a path to your image such as/images/logo.png.Now, activate theversion option:
12345
# config/packages/framework.yamlframework:# ...assets:version:'v2'12345678910111213
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:assetsversion="v2"/></framework:config></container>12345678
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{// ...$framework->assets() ->version('v2');};Now, the same asset will be rendered as/images/logo.png?v2 If you usethis feature, youmust manually increment theversion valuebefore each deployment so that the query parameters change.
You can also control how the query string works via theversion_formatoption.
Note
This parameter cannot be set at the same time asversion_strategy orjson_manifest_path.
Tip
As with all settings, you can use a parameter as value for theversion. This makes it easier to increment the cache on eachdeployment.
version_format
type:stringdefault:%%s?%%s
This specifies asprintf pattern that will be used with theversion option to construct an asset's path. By default, the patternadds the asset's version as a query string. For example, ifversion_format is set to%%s?version=%%s andversionis set to5, the asset's path would be/images/logo.png?version=5.
Note
All percentage signs (%) in the format string must be doubled toescape the character. Without escaping, values might inadvertently beinterpreted asService Container.
Tip
Some CDN's do not support cache-busting via query strings, so injectingthe version into the actual file path is necessary. Thankfully,version_format is not limited to producing versioned querystrings.
The pattern receives the asset's original path and version as its firstand second parameters, respectively. Since the asset's path is oneparameter, you cannot modify it in-place (e.g./images/logo-v5.png);however, you can prefix the asset's path using a pattern ofversion-%%2$s/%%1$s, which would result in the pathversion-5/images/logo.png.
URL rewrite rules could then be used to disregard the version prefixbefore serving the asset. Alternatively, you could copy assets to theappropriate version path as part of your deployment process and forgotany URL rewriting. The latter option is useful if you would like olderasset versions to remain accessible at their original URL.
version_strategy
type:stringdefault:null
The service id of theasset version strategyapplied to the assets. This option can be set globally for all assets andindividually for each asset package:
123456789101112131415
# config/packages/framework.yamlframework:assets:# this strategy is applied to every asset (including packages)version_strategy:'app.asset.my_versioning_strategy'packages:foo_package:# this package removes any versioning (its assets won't be versioned)version:~bar_package:# this package uses its own strategy (the default strategy is ignored)version_strategy:'app.asset.another_version_strategy'baz_package:# this package inherits the default strategybase_path:'/images'12345678910111213141516171819202122232425
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:assetsversion-strategy="app.asset.my_versioning_strategy"><!-- this package removes any versioning (its assets won't be versioned) --><framework:packagename="foo_package"version="null"/><!-- this package uses its own strategy (the default strategy is ignored) --><framework:packagename="bar_package"version-strategy="app.asset.another_version_strategy"/><!-- this package inherits the default strategy --><framework:packagename="baz_package"base_path="/images"/></framework:assets></framework:config></container>1234567891011121314151617181920
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{// ...$framework->assets() ->versionStrategy('app.asset.my_versioning_strategy');$framework->assets()->package('foo_package')// this package removes any versioning (its assets won't be versioned) ->version(null);$framework->assets()->package('bar_package')// this package uses its own strategy (the default strategy is ignored) ->versionStrategy('app.asset.another_version_strategy');$framework->assets()->package('baz_package')// this package inherits the default strategy ->basePath('/images');};Note
This parameter cannot be set at the same time asversion orjson_manifest_path.
cache
app
type:stringdefault:cache.adapter.filesystem
The cache adapter used by thecache.app service. The FrameworkBundleships with multiple adapters:cache.adapter.apcu,cache.adapter.system,cache.adapter.filesystem,cache.adapter.psr6,cache.adapter.redis,cache.adapter.memcached,cache.adapter.pdo andcache.adapter.doctrine_dbal.
There's also a special adapter calledcache.adapter.array which storescontents in memory using a PHP array and it's used to disable caching (mostly onthedev environment).
Tip
It might be tough to understand at the beginning, so to avoid confusionremember that all pools perform the same actions but on different mediumgiven the adapter they are based on. Internally, a pool wraps the definitionof an adapter.
default_doctrine_provider
type:string
The service name to use as your default Doctrine provider. The provider isavailable as thecache.default_doctrine_provider service.
default_memcached_provider
type:stringdefault:memcached://localhost
The DSN to use by the Memcached provider. The provider is available as thecache.default_memcached_providerservice.
default_pdo_provider
type:stringdefault:doctrine.dbal.default_connection
The service id of the database connection, which should be either a PDO or aDoctrine DBAL instance. The provider is available as thecache.default_pdo_providerservice.
default_psr6_provider
type:string
The service name to use as your default PSR-6 provider. It is available asthecache.default_psr6_provider service.
default_redis_provider
type:stringdefault:redis://localhost
The DSN to use by the Redis provider. The provider is available as thecache.default_redis_providerservice.
directory
type:stringdefault:%kernel.cache_dir%/pools
The path to the cache directory used by services inheriting from thecache.adapter.filesystem adapter (includingcache.app).
pools
type:array
A list of cache pools to be created by the framework extension.
See also
For more information about how pools work, seecache pools.
To configure a Redis cache pool with a default lifetime of 1 hour, do the following:
1234567
# config/packages/framework.yamlframework:cache:pools:cache.mycache:adapter:cache.adapter.redisdefault_lifetime:36001234567891011121314151617181920
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:cache><framework:poolname="cache.mycache"adapter="cache.adapter.redis"default-lifetime="3600" /></framework:cache><!-- ... --></framework:config></container>123456789
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->cache() ->pool('cache.mycache') ->adapters(['cache.adapter.redis']) ->defaultLifetime(3600);};adapter
type:stringdefault:cache.app
The service name of the adapter to use. You can specify one of the defaultservices that follow the patterncache.adapter.[type]. Alternatively youcan specify another cache pool as base, which will make this pool inherit thesettings from the base pool as defaults.
Note
Your service needs to implement thePsr\Cache\CacheItemPoolInterface interface.
clearer
type:string
The cache clearer used to clear your PSR-6 cache.
See also
For more information, seePsr6CacheClearer.
default_lifetime
type:integer |string
Default lifetime of your cache items. Give an integer value to set the defaultlifetime in seconds. A string value could be ISO 8601 time interval, like"PT5M"or a PHP date expression that is accepted bystrtotime(), like"5 minutes".
If no value is provided, the cache adapter will fallback to the default value onthe actual cache storage.
name
type:prototype
Name of the pool you want to create.
Note
Your pool name must differ fromcache.app orcache.system.
provider
type:string
Overwrite the default service name or DSN respectively, if you do not want touse what is configured asdefault_X_provider undercache. See thedescription of the default provider setting above for information on how tospecify your specific provider.
tags
type:boolean |stringdefault:null
Whether your service should be able to handle tags or not.Can also be the service id of another cache pool where tags will be stored.
prefix_seed
type:stringdefault:_%kernel.project_dir%.%kernel.container_class%
This value is used as part of the "namespace" generated for thecache item keys. A common practice is to use the unique name of the application(e.g.symfony.com) because that prevents naming collisions when deployingmultiple applications into the same path (on different servers) that share thesame cache backend.
It's also useful when usingblue/green deployment strategies and moregenerally, when you need to abstract out the actual deployment directory (forexample, when warming caches offline).
Note
Theprefix_seed option is used at compile time. This meansthat any change made to this value after container's compilationwill have no effect.
system
type:stringdefault:cache.adapter.system
The cache adapter used by thecache.system service. It supports the sameadapters available for thecache.app service.
csrf_protection
See also
For more information about CSRF protection, seeHow to Implement CSRF Protection.
enabled
type:booleandefault:true orfalse depending on your installation
This option can be used to disable CSRF protection onall forms. But youcan alsodisable CSRF protection on individual forms.
1234
# config/packages/framework.yamlframework:# ...csrf_protection:true12345678910111213
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:csrf-protectionenabled="true"/></framework:config></container>1234567
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->csrfProtection() ->enabled(true) ;};If you're using forms, but want to avoid starting your session (e.g. usingforms in an API-only website),csrf_protection will need to be set tofalse.
stateless_token_ids
type:arraydefault:[]
The list of CSRF token ids that will usestateless CSRF protection.
7.2
Thestateless_token_ids option was introduced in Symfony 7.2.
check_header
type:integer orbooldefault:false
Whether to check the CSRF token in an HTTP header in addition to the cookie whenusingstateless CSRF protection. You can also setthis to2 (the value of theCHECK_ONLY_HEADER constant on theSameOriginCsrfTokenManager class)to check only the header and ignore the cookie.
7.2
Thecheck_header option was introduced in Symfony 7.2.
cookie_name
type:stringdefault:csrf-token
The name of the cookie (and HTTP header) to use for the double-submit when usingstateless CSRF protection.
7.2
Thecookie_name option was introduced in Symfony 7.2.
default_locale
type:stringdefault:en
The default locale is used if no_locale routing parameter has beenset. It is available with theRequest::getDefaultLocalemethod.
See also
You can read more information about the default locale inTranslations.
enabled_locales
type:arraydefault:[] (empty array = enable all locales)
Symfony applications generate by default the translation files for validationand security messages in all locales. If your application only uses somelocales, use this option to restrict the files generated by Symfony and improveperformance a bit:
123
# config/packages/translation.yamlframework:enabled_locales:['en','es']1234567891011121314
<!-- config/packages/translation.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><enabled-locale>en</enabled-locale><enabled-locale>es</enabled-locale></framework:config></container>123456
// config/packages/translation.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->enabledLocales(['en','es']);};An added bonus of defining the enabled locales is that they are automaticallyadded as a requirement of thespecial _locale parameter.For example, if you define this value as['ar', 'he', 'ja', 'zh'], the_locale routing parameter will have anar|he|ja|zh requirement. If someuser makes requests with a locale not included in this option, they'll see a 404 error.
set_content_language_from_locale
type:booleandefault:false
If this option is set totrue, the response will have aContent-LanguageHTTP header set with theRequest locale.
set_locale_from_accept_language
type:booleandefault:false
If this option is set totrue, theRequest locale will automatically beset to the value of theAccept-Language HTTP header.
When the_locale request attribute is passed, theAccept-Language headeris ignored.
disallow_search_engine_index
type:booleandefault:true when the debug mode is enabled,false otherwise.
Iftrue, Symfony adds aX-Robots-Tag: noindex HTTP tag to all responses(unless your own app adds that header, in which case it's not modified). ThisX-Robots-Tag HTTP header tells search engines to not index your web site.This option is a protection measure in case you accidentally publish your sitein debug mode.
error_controller
type:stringdefault:error_controller
This is the controller that is called when an exception is thrown anywhere inyour application. The default controller(ErrorController)renders specific templates under different error conditions (seeHow to Customize Error Pages).
esi
See also
You can read more about Edge Side Includes (ESI) inWorking with Edge Side Includes.
enabled
type:booleandefault:false
Whether to enable the edge side includes support in the framework.
You can also setesi totrue to enable it:
123
# config/packages/framework.yamlframework:esi:true12345678910111213
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:esi/></framework:config></container>123456
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->esi()->enabled(true);};exceptions
type:array
Defines thelog level,log channeland HTTP status code applied to the exceptions that match the given exception class:
1234567
# config/packages/exceptions.yamlframework:exceptions:Symfony\Component\HttpKernel\Exception\BadRequestHttpException:log_level:'debug'status_code:422log_channel:'custom_channel'12345678910111213141516171819
<!-- config/packages/exceptions.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:exceptionclass="Symfony\Component\HttpKernel\Exception\BadRequestHttpException"log-level="debug"status-code="422"log-channel="custom_channel" /><!-- ... --></framework:config></container>1234567891011
// config/packages/exceptions.phpuseSymfony\Component\HttpKernel\Exception\BadRequestHttpException;useSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->exception(BadRequestHttpException::class) ->logLevel('debug') ->statusCode(422) ->logChannel('custom_channel') ;};7.3
Thelog_channel option was introduced in Symfony 7.3.
The order in which you configure exceptions is important because Symfony willuse the configuration of the first exception that matchesinstanceof:
12345678910
# config/packages/exceptions.yamlframework:exceptions:Exception:log_level:'debug'status_code:404# The following configuration will never be used because \RuntimeException extends \ExceptionRuntimeException:log_level:'debug'status_code:422You can map a status code and a set of headers to an exception thanksto the#[WithHttpStatus] attribute on the exception class:
1234567891011
namespaceApp\Exception;useSymfony\Component\HttpKernel\Attribute\WithHttpStatus;#[WithHttpStatus(422, ['Retry-After' =>10,'X-Custom-Header' =>'header-value',])]classCustomExceptionextends \Exception{}It is also possible to map a log level on a custom exception class usingthe#[WithLogLevel] attribute:
123456789
namespaceApp\Exception;usePsr\Log\LogLevel;useSymfony\Component\HttpKernel\Attribute\WithLogLevel;#[WithLogLevel(LogLevel::WARNING)]classCustomExceptionextends \Exception{}The attributes can also be added to interfaces directly:
123456789101112
namespaceApp\Exception;useSymfony\Component\HttpKernel\Attribute\WithHttpStatus;#[WithHttpStatus(422)]interfaceCustomExceptionInterface{}classCustomExceptionextends \ExceptionimplementsCustomExceptionInterface{}7.1
Support to use#[WithHttpStatus] and#[WithLogLevel] attributeson interfaces was introduced in Symfony 7.1.
form
enabled
type:booleandefault:true orfalse depending on your installation
Whether to enable the form services or not in the service container. Ifyou don't use forms, setting this tofalse may increase your application'sperformance because less services will be loaded into the container.
This option will automatically be set totrue when one of the childsettings is configured.
Note
This will automatically enable thevalidation.
See also
For more details, seeForms.
csrf_protection
field_name
type:stringdefault:_token
This is the field name that you should give to the CSRF token field of your forms.
field_attr
type:arraydefault:['data-controller' => 'csrf-protection']
HTML attributes to add to the CSRF token field of your forms.
token_id
type:stringdefault:null
The CSRF token ID used to validate the CSRF tokens of your forms. This settingapplies only to form types that useservice autoconfiguration,which typically means your own form types, not those registered by third-party bundles.
fragments
See also
Learn more about fragments in theHTTP Cache article.
enabled
type:booleandefault:false
Whether to enable the fragment listener or not. The fragment listener isused to render ESI fragments independently of the rest of the page.
This setting is automatically set totrue when one of the child settingsis configured.
hinclude_default_template
type:stringdefault:null
Sets the content shown during the loading of the fragment or when JavaScriptis disabled. This can be either a template name or the content itself.
See also
SeeCreating and Using Templates for more information about hinclude.
path
type:stringdefault:/_fragment
The path prefix for fragments. The fragment listener will only be executedwhen the request starts with this path.
handle_all_throwables
type:booleandefault:true
When set totrue, the Symfony kernel will catch all\Throwable exceptionsthrown by the application and will turn them into HTTP responses.
html_sanitizer
Thehtml_sanitizer option (and its children) are used to configurecustom HTML sanitizers. Read more about the options in theHTML sanitizer documentation.
http_cache
allow_reload
type:booleandefault:false
Specifies whether the client can force a cache reload by including aCache-Control "no-cache" directive in the request. Set it totruefor compliance with RFC 2616.
allow_revalidate
type:booleandefault:false
Specifies whether the client can force a cache revalidate by including aCache-Control "max-age=0" directive in the request. Set it totruefor compliance with RFC 2616.
debug
type:booleandefault:%kernel.debug%
If true, exceptions are thrown when things go wrong. Otherwise, the cache willtry to carry on and deliver a meaningful response.
default_ttl
type:integerdefault:0
The number of seconds that a cache entry should be considered fresh when noexplicit freshness information is provided in a response. ExplicitCache-Control or Expires headers override this value.
enabled
type:booleandefault:false
private_headers
type:arraydefault:['Authorization', 'Cookie']
Set of request headers that trigger "private" cache-control behavior on responsesthat don't explicitly state whether the response is public or private via aCache-Control directive.
skip_response_headers
type:arraydefault:Set-Cookie
Set of response headers that will never be cached even when the response is cacheableand public.
stale_if_error
type:integerdefault:60
Specifies the default number of seconds (the granularity is the second) duringwhich the cache can serve a stale response when an error is encountered.This setting is overridden by the stale-if-error HTTPCache-Control extension (see RFC 5861).
stale_while_revalidate
type:integerdefault:2
Specifies the default number of seconds (the granularity is the second as theResponse TTL precision is a second) during which the cache can immediately returna stale response while it revalidates it in the background.This setting is overridden by the stale-while-revalidate HTTP Cache-Controlextension (see RFC 5861).
trace_level
type:stringpossible values:'none','short' or'full'
For 'short', a concise trace of the main request will be added as an HTTP header.'full' will add traces for all requests (including ESI subrequests).(default:'full' if in debug;'none' otherwise)
http_client
When the HttpClient component is installed, an HTTP client is availableas a service namedhttp_client or using the autowiring aliasHttpClientInterface.
This service can be configured usingframework.http_client.default_options:
12345678
# config/packages/framework.yamlframework:# ...http_client:max_host_connections:10default_options:headers:{'X-Powered-By':'ACME App'}max_redirects:71234567891011121314151617
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:http-clientmax-host-connections="10"><framework:default-optionsmax-redirects="7"><framework:headername="X-Powered-By">ACME App</framework:header></framework:default-options></framework:http-client></framework:config></container>123456789101112
// config/packages/framework.php$container->loadFromExtension('framework', ['http_client' => ['max_host_connections' =>10,'default_options' => ['headers' => ['X-Powered-By' =>'ACME App', ],'max_redirects' =>7, ], ],]);123456
$client = HttpClient::create(['headers' => ['X-Powered-By' =>'ACME App', ],'max_redirects' =>7,],10);Multiple pre-configured HTTP client services can be defined, each with itsservice name defined as a key underscoped_clients. Scoped clients inheritthe default options defined for thehttp_client service. You can overridethese options and can define a few others:
12345678
# config/packages/framework.yamlframework:# ...http_client:scoped_clients:my_api.client:auth_bearer:secret_bearer_token# ...123456789101112131415
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:http-client><framework:scoped-clientname="my_api.client"auth-bearer="secret_bearer_token"/></framework:http-client></framework:config></container>1234567891011
// config/packages/framework.php$container->loadFromExtension('framework', ['http_client' => ['scoped_clients' => ['my_api.client' => ['auth_bearer' =>'secret_bearer_token',// ... ], ], ],]);1234
$client = HttpClient::createForBaseUri('https://...', ['auth_bearer' =>'secret_bearer_token',// ...]);Options defined for scoped clients apply only to URLs that match either theirbase_uri or thescope option when it is defined. Non-matching URLs alwaysuse default options.
Each scoped client also defines a corresponding named autowiring alias.If you use for exampleSymfony\Contracts\HttpClient\HttpClientInterface $myApiClientas the type and name of an argument, autowiring will inject themy_api.clientservice into your autowired classes.
auth_basic
type:string
The username and password used to create theAuthorization HTTP headerused in HTTP Basic authentication. The value of this option must follow theformatusername:password.
auth_bearer
type:string
The token used to create theAuthorization HTTP header used in HTTP Bearerauthentication (also called token authentication).
auth_ntlm
type:string
The username and password used to create theAuthorization HTTP header usedin theMicrosoft NTLM authentication protocol. The value of this option mustfollow the formatusername:password. This authentication mechanism requiresusing the cURL-based transport.
base_uri
type:string
URI that is merged into relative URIs, following the rules explained in theRFC 3986 standard. This is useful when all the requests you make share acommon prefix (e.g.https://api.github.com/) so you can avoid adding it toevery request.
Here are some common examples of howbase_uri merging works in practice:
bindto
type:string
A network interface name, IP address, a host name or a UNIX socket to use as theoutgoing network interface.
buffer
type:boolean |Closure
Buffering the response means that you can access its content multiple timeswithout performing the request again. Buffering is enabled by default when thecontent type of the response istext/*,application/json orapplication/xml.
If this option is a boolean value, the response is buffered when the value istrue. If this option is a closure, the response is buffered when thereturned value istrue (the closure receives as argument an array with theresponse headers).
cafile
type:string
The path of the certificate authority file that contains one or morecertificates used to verify the other servers' certificates.
ciphers
type:string
A list of the names of the ciphers allowed for the TLS connections. Theycan be separated by colons, commas or spaces (e.g.'RC4-SHA:TLS13-AES-128-GCM-SHA256').
crypto_method
type:integer
The minimum version of TLS to accept. The value must be one of theSTREAM_CRYPTO_METHOD_TLSv*_CLIENT constants defined by PHP.
extra
type:array
Arbitrary additional data to pass to the HTTP client for further use.This can be particularly useful whendecorating an existing client.
headers
type:array
An associative array of the HTTP headers added before making the request. Thisvalue must use the format['header-name' => 'value0, value1, ...'].
http_version
type:string |nulldefault:null
The HTTP version to use, typically'1.1' or'2.0'. Leave it tonullto let Symfony select the best version automatically.
local_cert
type:string
The path to a file that contains thePEM formatted certificate used by theHTTP client. This is often combined with thelocal_pk andpassphraseoptions.
local_pk
type:string
The path of a file that contains thePEM formatted private key of thecertificate defined in thelocal_cert option.
max_duration
type:floatdefault:0
The maximum execution time, in seconds, that the request and the response areallowed to take. A value lower than or equal to 0 means it is unlimited.
max_host_connections
type:integerdefault:6
Defines the maximum amount of simultaneously open connections to a single host(considering a "host" the same as a "host name + port number" pair). This limitalso applies for proxy connections, where the proxy is considered to be the hostfor which this limit is applied.
max_redirects
type:integerdefault:20
The maximum number of redirects to follow. Use0 to not follow anyredirection.
no_proxy
type:string |nulldefault:null
A comma separated list of hosts that do not require a proxy to be reached, evenif one is configured. Use the'*' wildcard to match all hosts and an emptystring to match none (disables the proxy).
passphrase
type:string
The passphrase used to encrypt the certificate stored in the file defined in thelocal_cert option.
peer_fingerprint
type:array
When negotiating a TLS connection, the server sends a certificateindicating its identity. A public key is extracted from this certificate and ifit does not exactly match any of the public keys provided in this option, theconnection is aborted before sending or receiving any data.
The value of this option is an associative array ofalgorithm => hash(e.g['pin-sha256' => '...']).
proxy
type:string |null
The HTTP proxy to use to make the requests. Leave it tonull to detect theproxy automatically based on your system configuration.
query
type:array
An associative array of the query string values added to the URL before makingthe request. This value must use the format['parameter-name' => parameter-value, ...].
rate_limiter
type:string
The service ID of the rate limiter used to limit the number of HTTP requestswithin a certain period. The service must implement theLimiterInterface.
7.1
Therate_limiter option was introduced in Symfony 7.1.
resolve
type:array
A list of hostnames and their IP addresses to pre-populate the DNS cache used bythe HTTP client in order to avoid a DNS lookup for those hosts. This option isuseful to improve security when IPs are checked before the URL is passed to theclient and to make your tests easier.
The value of this option is an associative array ofdomain => IP address(e.g['symfony.com' => '46.137.106.254', ...]).
retry_failed
type:array
This option configures the behavior of the HTTP client when some request fails,including which types of requests to retry and how many times. The behavior isdefined with the following options:
1234567891011121314151617181920212223
# config/packages/framework.yamlframework:# ...http_client:# ...default_options:retry_failed:# retry_strategy: app.custom_strategyhttp_codes:0:['GET','HEAD']# retry network errors if request method is GET or HEAD429:true# retry all responses with 429 status code500:['GET','HEAD']max_retries:2delay:1000multiplier:3max_delay:5000jitter:0.3scoped_clients:my_api.client:# ...retry_failed:max_retries:4delay
type:integerdefault:1000
The initial delay in milliseconds used to compute the waiting time between retries.
enabled
type:booleandefault:false
Whether to enable the support for retry failed HTTP request or not.This setting is automatically set to true when one of the child settings is configured.
http_codes
type:arraydefault:DEFAULT_RETRY_STATUS_CODES()
The list of HTTP status codes that triggers a retry of the request.
jitter
type:floatdefault:0.1 (must be between 0.0 and 1.0)
This option adds some randomness to the delay. It's useful to avoid sendingmultiple requests to the server at the exact same time. The randomness iscalculated asdelay * jitter. For example: if delay is1000ms and jitteris0.2, the actual delay will be a number between800 and1200 (1000 +/- 20%).
max_delay
type:integerdefault:0
The maximum amount of milliseconds initial to wait between retries.Use0 to not limit the duration.
max_retries
type:integerdefault:3
The maximum number of retries for failing requests. When the maximum is reached,the client returns the last received response.
multiplier
type:floatdefault:2
This value is multiplied to the delay each time a retry occurs, to distributeretries in time instead of making all of them sequentially.
retry_strategy
type:string
The service is used to decide if a request should be retried and to compute thetime to wait between retries. By default, it uses an instance ofGenericRetryStrategy configuredwithhttp_codes,delay,max_delay,multiplier andjitteroptions. This class has to implementRetryStrategyInterface.
scope
type:string
For scoped clients only: the regular expression that the URL must match beforeapplying all other non-default options. By default, the scope is derived frombase_uri.
timeout
type:floatdefault: depends on your PHP config
Time, in seconds, to wait for network activity. If the connection is idle for longer, aTransportException is thrown.Its default value is the same as the value of PHP'sdefault_socket_timeoutconfig option.
verify_host
type:booleandefault:true
Iftrue, the certificate sent by other servers is verified to ensure thattheir common name matches the host included in the URL. This is usuallycombined withverify_peer to also verify the certificate authenticity.
verify_peer
type:booleandefault:true
Iftrue, the certificate sent by other servers when negotiating a TLSconnection is verified for authenticity. Authenticating the certificate is notenough to be sure about the server, so you should combine this with theverify_host option.
http_method_override
type:booleandefault:false
This determines whether the_method request parameter is used as theintended HTTP method on POST requests. If enabled, theRequest::enableHttpMethodParameterOverridemethod gets called automatically. It becomes the service container parameternamedkernel.http_method_override.
See also
Changing the Action and HTTP Method ofSymfony forms.
Warning
If you're using theHttpCache Reverse Proxywith this option, the kernel will ignore the_method parameter,which could lead to errors.
To fix this, invoke theenableHttpMethodParameterOverride() methodbefore creating theRequest object:
12345678
// public/index.php// ...$kernel =newCacheKernel($kernel);Request::enableHttpMethodParameterOverride();// <-- add this line$request = Request::createFromGlobals();// ...ide
type:stringdefault:%env(default::SYMFONY_IDE)%
Symfony turns file paths seen in variable dumps and exception messages intolinks that open those files right inside your browser. If you prefer to openthose files in your favorite IDE or text editor, set this option to any of thefollowing values:phpstorm,sublime,textmate,macvim,emacs,atom andvscode.
Note
Thephpstorm option is supported natively by PhpStorm on macOS andWindows; Linux requires installingphpstorm-url-handler.
If you use another editor, the expected configuration value is a URL templatethat contains an%f placeholder where the file path is expected and%lplaceholder for the line number (percentage signs (%) must be escaped bydoubling them to prevent Symfony from interpreting them as container parameters).
123
# config/packages/framework.yamlframework:ide:'myide://open?url=file://%%f&line=%%l'1234567891011
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:configide="myide://open?url=file://%%f&line=%%l"/></container>123456
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->ide('myide://open?url=file://%%f&line=%%l');};Since every developer uses a different IDE, the recommended way to enable thisfeature is to configure it on a system level. First, you can define this optionin theSYMFONY_IDE environment variable, which Symfony reads automaticallywhenframework.ide config is not set.
Another alternative is to set thexdebug.file_link_format option in yourphp.ini configuration file. The format to use is the same as for theframework.ide option, but without the need to escape the percent signs(%) by doubling them:
12345678
// example for PhpStormxdebug.file_link_format="phpstorm://open?file=%f&line=%l"// example for PhpStorm with Jetbrains Toolboxxdebug.file_link_format="jetbrains://phpstorm/navigate/reference?project=example&path=%f:%l"// example for Sublime Textxdebug.file_link_format="subl://open?url=file://%f&line=%l"Note
If bothframework.ide andxdebug.file_link_format are defined,Symfony uses the value of thexdebug.file_link_format option.
Tip
Setting thexdebug.file_link_format ini option works even if the Xdebugextension is not enabled.
Tip
When running your app in a container or in a virtual machine, you can tellSymfony to map files from the guest to the host by changing their prefix.This map should be specified at the end of the URL template, using& and> as guest-to-host separators:
1234567
// /path/to/guest/.../file will be opened// as /path/to/host/.../file on the host// and /var/www/app/ as /projects/my_project/ also'myide://%%f:%%l&/path/to/guest/>/path/to/host/&/var/www/app/>/projects/my_project/&...'// example for PhpStorm'phpstorm://open?file=%%f&line=%%l&/var/www/app/>/projects/my_project/'lock
type:string |array
The default lock adapter. If not defined, the value is set tosemaphore whenavailable, or toflock otherwise. Store's DSN are also allowed.
enabled
type:booleandefault:true
Whether to enable the support for lock or not. This setting isautomatically set totrue when one of the child settings is configured.
resources
type:array
A map of lock stores to be created by the framework extension, withthe name as key and DSN or service id as value:
123
# config/packages/lock.yamlframework:lock:'%env(LOCK_DSN)%'123456789101112131415
<!-- config/packages/lock.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:lock><framework:resourcename="default">%env(LOCK_DSN)%</framework:resource></framework:lock></framework:config></container>1234567
// config/packages/lock.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->lock() ->resource('default', [env('LOCK_DSN')]);};See also
For more details, seeDealing with Concurrency with Locks.
mailer
dsn
type:stringdefault:null
The DSN used by the mailer. When several DSN may be used, usetransports option (see below) instead.
envelope
recipients
type:array
The "envelope recipient" which is used as the value ofRCPT TO during thetheSMTP session. This value overrides any other recipient set in the code.
123456
# config/packages/mailer.yamlframework:mailer:dsn:'smtp://localhost:25'envelope:recipients:['admin@symfony.com','lead@symfony.com']1234567891011121314151617
<!-- config/packages/mailer.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:mailerdsn="smtp://localhost:25"><framework:envelope><framework:recipient>admin@symfony.com</framework:recipient><framework:recipient>lead@symfony.com</framework:recipient></framework:envelope></framework:mailer></framework:config></container>12345678910111213141516
// config/packages/mailer.phpnamespaceSymfony\Component\DependencyInjection\Loader\Configurator;returnstaticfunction(ContainerConfigurator$container):void{$container->extension('framework', ['mailer' => ['dsn' =>'smtp://localhost:25','envelope' => ['recipients' => ['admin@symfony.com','lead@symfony.com', ], ], ], ]);};sender
type:string
The "envelope sender" which is used as the value ofMAIL FROM during theSMTP session. This value overrides any other sender set in the code.
headers
type:array
Headers to add to emails. The key (name attribute in xml format) is theheader name and value the header value.
See also
For more information, seeConfiguring Emails Globally
message_bus
type:stringdefault:null or default bus if Messenger component is installed
Service identifier of the message bus to use when using theMessenger component (e.g.messenger.default_bus).
transports
type:array
Alist of DSN that can be used by themailer. A transport name is the key and the dsn is the value.
messenger
enabled
type:booleandefault:true
Whether to enable or not Messenger.
See also
For more details, see theMessenger componentdocumentation.
php_errors
log
type:boolean,int orarray<int, string>default:true
Use the application logger instead of the PHP logger for logging PHP errors.When an integer value is used, it defines a bitmask of PHP errors that willbe logged. Those integer values must be the same used in theerror_reporting PHP option. The default log levels will be used for eachPHP error.When a boolean value is used,true enables logging for all PHP errorswhilefalse disables logging entirely.
This option also accepts a map of PHP errors to log levels:
12345678910111213141516171819
# config/packages/framework.yamlframework:php_errors:log:!php/const\E_DEPRECATED:!php/constPsr\Log\LogLevel::ERROR!php/const\E_USER_DEPRECATED:!php/constPsr\Log\LogLevel::ERROR!php/const\E_NOTICE:!php/constPsr\Log\LogLevel::ERROR!php/const\E_USER_NOTICE:!php/constPsr\Log\LogLevel::ERROR!php/const\E_STRICT:!php/constPsr\Log\LogLevel::ERROR!php/const\E_WARNING:!php/constPsr\Log\LogLevel::ERROR!php/const\E_USER_WARNING:!php/constPsr\Log\LogLevel::ERROR!php/const\E_COMPILE_WARNING:!php/constPsr\Log\LogLevel::ERROR!php/const\E_CORE_WARNING:!php/constPsr\Log\LogLevel::ERROR!php/const\E_USER_ERROR:!php/constPsr\Log\LogLevel::CRITICAL!php/const\E_RECOVERABLE_ERROR:!php/constPsr\Log\LogLevel::CRITICAL!php/const\E_COMPILE_ERROR:!php/constPsr\Log\LogLevel::CRITICAL!php/const\E_PARSE:!php/constPsr\Log\LogLevel::CRITICAL!php/const\E_ERROR:!php/constPsr\Log\LogLevel::CRITICAL!php/const\E_CORE_ERROR:!php/constPsr\Log\LogLevel::CRITICAL123456789101112131415161718
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><!-- in XML configuration you cannot use PHP constants as the value of the 'type' attribute, which makes this format way less readable. Consider using YAML or PHP for this configuration --><framework:logtype="8"logLevel="error"/><framework:logtype="2"logLevel="error"/><!-- ... --></framework:config></container>123456789
// config/packages/framework.phpusePsr\Log\LogLevel;useSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->phpErrors()->log(\E_DEPRECATED, LogLevel::ERROR);$framework->phpErrors()->log(\E_USER_DEPRECATED, LogLevel::ERROR);// ...};throw
type:booleandefault:%kernel.debug%
Throw PHP errors as\ErrorException instances. The parameterdebug.error_handler.throw_at controls the threshold.
profiler
collect
type:booleandefault:true
This option configures the way the profiler behaves when it is enabled. If settotrue, the profiler collects data for all requests. If you want to onlycollect information on-demand, you can set thecollect flag tofalse andactivate the data collectors manually:
1
$profiler->enable();collect_parameter
type:stringdefault:null
This specifies name of a query parameter, a body parameter or a request attributeused to enable or disable collection of data by the profiler for each request.Combine it with thecollect option to enable/disable the profiler on demand:
- If the
collectoption is set totruebut this parameter exists in arequest and has any value other thantrue,yes,onor1, therequest data will not be collected; - If the
collectoption is set tofalse, but this parameter exists in arequest and has value oftrue,yes,onor1, the request datawill be collected.
collect_serializer_data
type:booleandefault:false
When this option istrue, all normalizers and encoders aredecorated by traceable implementations that collect profiling information about them.
7.3
Setting thecollect_serializer_data option tofalse is deprecatedsince Symfony 7.3.
dsn
type:stringdefault:file:%kernel.cache_dir%/profiler
The DSN where to store the profiling information.
enabled
type:booleandefault:false
The profiler can be enabled by setting this option totrue. When youinstall it using Symfony Flex, the profiler is enabled in thedevandtest environments.
Note
The profiler works independently from the Web Developer Toolbar, seetheWebProfilerBundle configurationon how to disable/enable the toolbar.
only_exceptions
type:booleandefault:false
When this is set totrue, the profiler will only be enabled when anexception is thrown during the handling of the request.
only_main_requests
type:booleandefault:false
When this is set totrue, the profiler will only be enabled on the mainrequests (and not on the subrequests).
property_access
magic_call
type:booleandefault:false
When enabled, theproperty_accessor service uses PHP'smagic __call() method whenitsgetValue() method is called.
magic_get
type:booleandefault:true
When enabled, theproperty_accessor service uses PHP'smagic __get() method whenitsgetValue() method is called.
magic_set
type:booleandefault:true
When enabled, theproperty_accessor service uses PHP'smagic __set() method whenitssetValue() method is called.
throw_exception_on_invalid_index
type:booleandefault:false
When enabled, theproperty_accessor service throws an exception when youtry to access an invalid index of an array.
throw_exception_on_invalid_property_path
type:booleandefault:true
When enabled, theproperty_accessor service throws an exception when youtry to access an invalid property path of an object.
property_info
enabled
type:booleandefault:true orfalse depending on your installation
with_constructor_extractor
type:booleandefault:false
Configures theproperty_info service to extract property information from the constructor argumentsusing theConstructorExtractor.
7.3
Thewith_constructor_extractor option was introduced in Symfony 7.3.It's required to set a value for it because its default value will changefromfalse totrue in Symfony 8.0.
rate_limiter
name
type:prototype
Name of the rate limiter you want to create.
lock_factory
type:stringdefault:lock.factory
The service that is used to create a lock. The service has to be an instance oftheLockFactory class.
policy
type:stringrequired
The name of the rate limiting algorithm to use. Example names arefixed_window,sliding_window andno_limit. SeeRate Limiter Policies)for more information.
request
formats
type:arraydefault:[]
This setting is used to associate additional request formats (e.g.html)to one or more mime types (e.g.text/html), which will allow you to use theformat & mime types to callRequest::getFormat($mimeType) orRequest::getMimeType($format).
In practice, this is important because Symfony uses it to automatically set theContent-Type header on theResponse (if you don't explicitly set one).If you pass an array of mime types, the first will be used for the header.
To configure ajsonp format:
12345
# config/packages/framework.yamlframework:request:formats:jsonp:'application/javascript'12345678910111213141516171819
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:request><framework:formatname="jsonp"><framework:mime-type>application/javascript</framework:mime-type></framework:format></framework:request></framework:config></container>1234567
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->request() ->format('jsonp','application/javascript');};router
cache_dir
type:stringdefault:%kernel.cache_dir%
The directory where routing information will be cached. Can be set to~ (null) to disable route caching.
7.1
Setting thecache_dir option is deprecated since Symfony 7.1. The routesare now always cached in the%kernel.build_dir% directory.
default_uri
type:string
The default URI used to generate URLs in a non-HTTP context (seeGenerating URLs in Commands).
http_port
type:integerdefault:80
The port for normal http requests (this is used when matching the scheme).
https_port
type:integerdefault:443
The port for https requests (this is used when matching the scheme).
resource
type:stringrequired
The path the main routing resource (e.g. a YAML file) that contains theroutes and imports the router should load.
strict_requirements
type:mixeddefault:true
Determines the routing generator behavior. When generating a route thathas specificparameter requirements, the generatorcan behave differently in case the used parameters do not meet these requirements.
The value can be one of:
true- Throw an exception when the requirements are not met;
false- Disable exceptions when the requirements are not met and return
''instead; null- Disable checking the requirements (thus, match the route even when therequirements don't match).
true is recommended in the development environment, whilefalseornull might be preferred in production.
type
type:string
The type of the resource to hint the loaders about the format. This isn'tneeded when you use the default routers with the expected file extensions(.xml,.yaml,.php).
utf8
type:booleandefault:true
When this option is set totrue, the regular expressions used in therequirements of route parameters will be runusing theutf-8 modifier. This will for example match any UTF-8 characterwhen using., instead of matching only a single byte.
If the charset of your application is UTF-8 (as defined in thegetCharset() method of your kernel) it'srecommended setting it totrue. This will make non-UTF8 URLs to generate 404errors.
secret
type:stringrequired
This is a string that should be unique to your application and it's commonlyused to add more entropy to security related operations. Its value shouldbe a series of characters, numbers and symbols chosen randomly and therecommended length is around 32 characters.
In practice, Symfony uses this value for encrypting the cookies usedin theremember me functionality and forcreating signed URIs when usingESI (Edge Side Includes).That's why you should treat this value as if it were a sensitive credential andnever make it public.
This option becomes the service container parameter namedkernel.secret,which you can use whenever the application needs an immutable random stringto add more entropy.
As with any other security-related parameter, it is a good practice to changethis value from time to time. However, keep in mind that changing this valuewill invalidate all signed URIs and Remember Me cookies. That's why, afterchanging this value, you should regenerate the application cache and logout all the application users.
secrets
decryption_env_var
type:stringdefault:base64:default::SYMFONY_DECRYPTION_SECRET
The env var name that contains the vault decryption secret. By default, thisvalue will be decoded from base64.
local_dotenv_file
type:stringdefault:%kernel.project_dir%/.env.%kernel.environment%.local
The path to the local.env file. This file must contain the vaultdecryption key, given by thedecryption_env_var option.
vault_directory
type:stringdefault:%kernel.project_dir%/config/secrets/%kernel.runtime_environment%
The directory to store the secret vault. By default, the path includes the valueof thekernel.runtime_environmentparameter.
semaphore
type:string |array
The default semaphore adapter. Store's DSN are also allowed.
enabled
type:booleandefault:true
Whether to enable the support for semaphore or not. This setting isautomatically set totrue when one of the child settings is configured.
resources
type:array
A map of semaphore stores to be created by the framework extension, withthe name as key and DSN or service id as value:
123
# config/packages/semaphore.yamlframework:semaphore:'%env(SEMAPHORE_DSN)%'123456789101112131415
<!-- config/packages/semaphore.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:semaphore><framework:resourcename="default">%env(SEMAPHORE_DSN)%</framework:resource></framework:semaphore></framework:config></container>12345678
// config/packages/semaphore.phpuseSymfony\Config\FrameworkConfig;usefunctionSymfony\Component\DependencyInjection\Loader\Configurator\env;returnstaticfunction(FrameworkConfig$framework):void{$framework->semaphore() ->resource('default', [env('SEMAPHORE_DSN')]);};serializer
circular_reference_handler
typestring
The service id that is used as the circular reference handler of the defaultserializer. The service has to implement the magic__invoke($object)method.
See also
For more information, seeHow to Use the Serializer.
default_context
type:arraydefault:[]
A map with default context options that will be used with eachserialize anddeserializecall. This can be used for example to set the json encoding behavior by settingjson_encode_optionsto ajson_encode flags bitmask.
You can inspect theserializer context buildersto discover the available settings.
enable_attributes
type:booleandefault:true
Enables support forPHP attributes in the serializer component.
See also
Seethe reference for a list of supported annotations.
enabled
type:booleandefault:true orfalse depending on your installation
Whether to enable theserializer service or not in the service container.
mapping
paths
type:arraydefault:[]
This option allows to define an array of paths with files or directories wherethe component will look for additional serialization files.
name_converter
type:string
The name converter to use.TheCamelCaseToSnakeCaseNameConvertername converter can enabled by using theserializer.name_converter.camel_case_to_snake_casevalue.
See also
For more information, seeHow to Use the Serializer.
session
cache_limiter
type:stringdefault:0
If set to0, Symfony won't set any particular header related to the cacheand it will rely onphp.ini'ssession.cache_limiter directive.
Unlike the other session options,cache_limiter is set as a regularcontainer parameter:
1234
# config/services.yamlparameters:session.storage.options:cache_limiter:012345678910111213
<!-- config/services.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd"><parameters><parameterkey="session.storage.options"type="collection"><parameterkey="cache_limiter">0</parameter></parameter></parameters></container>1234
// config/services.php$container->setParameter('session.storage.options', ['cache_limiter' =>0,]);Be aware that if you configure it, you'll have to set other session-related optionsas parameters as well.
cookie_domain
type:string
This determines the domain to set in the session cookie.
If not set,php.ini'ssession.cookie_domain directive will be relied on.
cookie_httponly
type:booleandefault:true
This determines whether cookies should only be accessible through the HTTPprotocol. This means that the cookie won't be accessible by scriptinglanguages, such as JavaScript. This setting can effectively help to reduceidentity theft throughXSS attacks.
cookie_lifetime
type:integer
This determines the lifetime of the session - in seconds.Setting this value to0 means the cookie is valid forthe length of the browser session.
If not set,php.ini'ssession.cookie_lifetime directive will be relied on.
cookie_path
type:string
This determines the path to set in the session cookie.
If not set,php.ini'ssession.cookie_path directive will be relied on.
cookie_samesite
type:string ornulldefault:'lax'
It controls the way cookies are sent when the HTTP request did not originatefrom the same domain that is associated with the cookies. Setting this option isrecommended to mitigateCSRF security attacks.
By default, browsers send all cookies related to the domain of the HTTP request.This may be a problem for example when you visit a forum and some maliciouscomment includes a link likehttps://some-bank.com/?send_money_to=attacker&amount=1000.If you were previously logged into your bank website, the browser will send allthose cookies when making that HTTP request.
The possible values for this option are:
null, usephp.ini'ssession.cookie_samesite directive.'none'(or theSymfony\Component\HttpFoundation\Cookie::SAMESITE_NONEconstant), use it to allowsending of cookies when the HTTP request originated from a different domain(previously this was the default behavior of null, but in newer browsers'lax'would be applied when the header has not been set)'strict'(or theCookie::SAMESITE_STRICTconstant), use it to neversend any cookie when the HTTP request did not originate from the same domain.'lax'(or theCookie::SAMESITE_LAXconstant), use it to allow sendingcookies when the request originated from a different domain, but only when theuser consciously made the request (by clicking a link or submitting a formwith theGETmethod).
cookie_secure
type:boolean or'auto'
This determines whether cookies should only be sent over secure connections. Inaddition totrue andfalse, there's a special'auto' value thatmeanstrue for HTTPS requests andfalse for HTTP requests.
If not set,php.ini'ssession.cookie_secure directive will be relied on.
enabled
type:booleandefault:true
Whether to enable the session support in the framework.
1234
# config/packages/framework.yamlframework:session:enabled:true12345678910111213
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:sessionenabled="true"/></framework:config></container>1234567
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->session() ->enabled(true);};gc_divisor
type:integer
Seegc_probability.
If not set,php.ini'ssession.gc_divisor directive will be relied on.
gc_maxlifetime
type:integer
This determines the number of seconds after which data will be seen as "garbage"and potentially cleaned up. Garbage collection may occur during sessionstart and depends ongc_divisor andgc_probability.
If not set,php.ini'ssession.gc_maxlifetime directive will be relied on.
gc_probability
type:integer
This defines the probability that the garbage collector (GC) process isstarted on every session initialization. The probability is calculated byusinggc_probability /gc_divisor, e.g. 1/100 means there is a 1%chance that the GC process will start on each request.
If not set, Symfony will use the value of thesession.gc_probability directivein thephp.ini configuration file.
7.2
Relying onphp.ini's directive as default forgc_probability wasintroduced in Symfony 7.2.
handler_id
type:string |nulldefault:null
Ifframework.session.save_path is not set, the default value of this optionisnull, which means to use the session handler configured in php.ini. If theframework.session.save_path option is set, then Symfony stores sessions usingthe native file session handler.
It is possible tostore sessions in a database,and also to configure the session handler with a DSN:
12345678
# config/packages/framework.yamlframework:session:# a few possible exampleshandler_id:'redis://localhost'handler_id:'%env(REDIS_URL)%'handler_id:'%env(DATABASE_URL)%'handler_id:'file://%kernel.project_dir%/var/sessions'1234567891011121314151617
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><!-- a few possible examples --><framework:sessionenabled="true"handler-id="redis://localhost"handler-id="%env(REDIS_URL)%"handler-id="%env(DATABASE_URL)%"handler-id="file://%kernel.project_dir%/var/sessions"/></framework:config></container>1234567891011121314
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;usefunctionSymfony\Component\DependencyInjection\Loader\Configurator\env;returnstaticfunction(FrameworkConfig$framework):void{// ...$framework->session()// a few possible examples ->handlerId('redis://localhost') ->handlerId(env('REDIS_URL')) ->handlerId(env('DATABASE_URL')) ->handlerId('file://%kernel.project_dir%/var/sessions');};Note
Supported DSN protocols are the following:
fileredisrediss(Redis over TLS)memcached(requiressymfony/cache)pdo_oci(requiresdoctrine/dbal)mssqlmysqlmysql2pgsqlpostgrespostgresqlsqlsrvsqlitesqlite3
metadata_update_threshold
type:integerdefault:0
This is how many seconds to wait between updating/writing the session metadata.This can be useful if, for some reason, you want to limit the frequency at whichthe session persists, instead of doing that on every request.
name
type:string
This specifies the name of the session cookie.
If not set,php.ini'ssession.name directive will be relied on.
save_path
type:string |nulldefault:%kernel.cache_dir%/sessions
This determines the argument to be passed to the save handler. If you choosethe default file handler, this is the path where the session files are created.
Ifnull,php.ini'ssession.save_path directive will be relied on:
1234
# config/packages/framework.yamlframework:session:save_path:~12345678910111213
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:sessionsave-path="null"/></framework:config></container>1234567
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->session() ->savePath(null);};sid_bits_per_character
type:integer
This determines the number of bits in the encoded session ID character. The possiblevalues are4 (0-9, a-f),5 (0-9, a-v), and6 (0-9, a-z, A-Z, "-", ",").The more bits results in stronger session ID.5 is recommended value formost environments.
If not set,php.ini'ssession.sid_bits_per_character directive will be relied on.
7.2
Thesid_bits_per_character option was deprecated in Symfony 7.2. No alternativeis provided as PHP 8.4 has deprecated the related option.
sid_length
type:integer
This determines the length of session ID string, which can be an integer between22 and256 (both inclusive),32 being the recommended value. Longersession IDs are harder to guess.
If not set,php.ini'ssession.sid_length directive will be relied on.
7.2
Thesid_length option was deprecated in Symfony 7.2. No alternative isprovided as PHP 8.4 has deprecated the related option.
storage_factory_id
type:stringdefault:session.storage.factory.native
The service ID used for creating theSessionStorageInterface that storesthe session. This service is available in the Symfony application via thesession.storage.factory service alias. The class has to implementSessionStorageFactoryInterface.To see a list of all available storages, run:
1
$php bin/console debug:container session.storage.factory.use_cookies
type:boolean
This specifies if the session ID is stored on the client side using cookies ornot.
If not set,php.ini'ssession.use_cookies directive will be relied on.
test
type:boolean
If this configuration setting is present (and notfalse), then the servicesrelated to testing your application (e.g.test.client) are loaded. Thissetting should be present in yourtest environment (usually viaconfig/packages/test/framework.yaml).
See also
For more information, seeTesting.
translator
cache_dir
type:string |nulldefault:%kernel.cache_dir%/translations
Defines the directory where the translation cache is stored. Usenull todisable this cache.
default_path
type:stringdefault:%kernel.project_dir%/translations
This option allows to define the path where the application translations filesare stored.
enabled
type:booleandefault:true orfalse depending on your installation
Whether or not to enable thetranslator service in the service container.
fallbacks
type:string|arraydefault: value ofdefault_locale
This option is used when the translation key for the current locale wasn'tfound.
See also
For more details, seeTranslations.
formatter
type:stringdefault:translator.formatter.default
The ID of the service used to format translation messages. The service classmust implement theMessageFormatterInterface.
logging
default:true when the debug mode is enabled,false otherwise.
Whentrue, a log entry is made whenever the translator cannot find a translationfor a given key. The logs are made to thetranslation channel at thedebug level for keys where there is a translation in the fallbacklocale, and thewarning level if there is no translation to use at all.
paths
type:arraydefault:[]
This option allows to define an array of paths where the component will lookfor translation files. The later a path is added, the more priority it has(translations from later paths overwrite earlier ones). Translations from thedefault_path have more priority thantranslations from all these paths.
providers
type:arraydefault:[]
This option enables and configurestranslation providersto push and pull your translations to/from third party translation services.
trust_x_sendfile_type_header
type:booleandefault:%env(bool:default::SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER)%
7.2
In Symfony 7.2, the default value of this option was changed fromfalse to thevalue stored in theSYMFONY_TRUST_X_SENDFILE_TYPE_HEADER environment variable.
X-Sendfile is a special HTTP header that tells web servers to replace theresponse contents by the file that is defined in that header. This improvesperformance because files are no longer served by your application but directlyby the web server.
This configuration option determines whether to trustx-sendfile header forBinaryFileResponse. If enabled, Symfony calls theBinaryFileResponse::trustXSendfileTypeHeadermethod automatically. It becomes the service container parameter namedkernel.trust_x_sendfile_type_header.
trusted_headers
Thetrusted_headers option is needed to configure which client informationshould be trusted (e.g. their host) when running Symfony behind a load balanceror a reverse proxy. SeeHow to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy.
trusted_hosts
type:array |stringdefault:['%env(default::SYMFONY_TRUSTED_HOSTS)%']
7.2
In Symfony 7.2, the default value of this option was changed from[] to thevalue stored in theSYMFONY_TRUSTED_HOSTS environment variable.
A lot of different attacks have been discovered relying on inconsistenciesin handling theHost header by various software (web servers, reverseproxies, web frameworks, etc.). Basically, every time the framework isgenerating an absolute URL (when sending an email to reset a password forinstance), the host might have been manipulated by an attacker.
See also
You can readHTTP Host header attacks for more information aboutthese kinds of attacks.
The SymfonyRequest::getHost()method might be vulnerable to some of these attacks because it depends onthe configuration of your web server. One simple solution to avoid theseattacks is to configure a list of hosts that your Symfony application can respondto. That's the purpose of thistrusted_hosts option. If the incomingrequest's hostname doesn't match one of the regular expressions in this list,the application won't respond and the user will receive a 400 response.
123
# config/packages/framework.yamlframework:trusted_hosts:['^example\.com$','^example\.org$']123456789101112131415
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:trusted-host>^example\.com$</framework:trusted-host><framework:trusted-host>^example\.org$</framework:trusted-host><!-- ... --></framework:config></container>123456
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->trustedHosts(['^example\.com$','^example\.org$']);};Hosts can also be configured to respond to any subdomain, via^(.+\.)?example\.com$ for instance.
In addition, you can also set the trusted hosts in the front controllerusing theRequest::setTrustedHosts() method:
12
// public/index.phpRequest::setTrustedHosts(['^(.+\.)?example\.com$','^(.+\.)?example\.org$']);The default value for this option is an empty array, meaning that the applicationcan respond to any given host.
See also
Read more about this in theSecurity Advisory Blog post.
trusted_proxies
Thetrusted_proxies option is needed to get precise information about theclient (e.g. their IP address) when running Symfony behind a load balancer or areverse proxy. SeeHow to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy.
validation
auto_mapping
type:arraydefault:[]
Defines the Doctrine entities that will be introspected to addautomatic validation constraints to them:
1234567
framework:validation:auto_mapping:# an empty array means that all entities that belong to that# namespace will add automatic validation'App\Entity\': [] 'Foo\':['Foo\Some\Entity','Foo\Another\Entity']1234567891011121314151617181920
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:validation><framework:auto-mapping><framework:servicenamespace="App\Entity\"/><framework:servicenamespace="Foo\">Foo\Some\Entity</framework:service><framework:servicenamespace="Foo\">Foo\Another\Entity</framework:service></framework:auto-mapping></framework:validation></framework:config></container>1234567891011
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->validation() ->autoMapping() ->paths(['App\\Entity\\' => [],'Foo\\' => ['Foo\\Some\\Entity','Foo\\Another\\Entity'], ]);};disable_translation
type:booleandefault:false
Validation error messages are automatically translated to the current applicationlocale. Set this option totrue to disable translation of validation messages.This is useful to avoid "missing translation" errors in applications that useonly a single language.
7.3
Thedisable_translation option was introduced in Symfony 7.3.
email_validation_mode
type:stringdefault:html5
Sets the default value for the"mode" option of the Email validator.
enable_attributes
type:booleandefault:true
If this option is enabled, validation constraints can be defined usingPHP attributes.
enabled
type:booleandefault:true orfalse depending on your installation
Whether or not to enable validation support.
This option will automatically be set totrue when one of the childsettings is configured.
mapping
paths
type:arraydefault:['config/validation/']
This option allows to define an array of paths with files or directories wherethe component will look for additional validation files:
123456
# config/packages/framework.yamlframework:validation:mapping:paths:-"%kernel.project_dir%/config/validation/"1234567891011121314151617
<!-- config/packages/framework.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:validation><framework:mapping><framework:path>%kernel.project_dir%/config/validation/</framework:path></framework:mapping></framework:validation></framework:config></container>12345678
// config/packages/framework.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->validation() ->mapping() ->paths(['%kernel.project_dir%/config/validation/']);};not_compromised_password
TheNotCompromisedPasswordconstraint makes HTTP requests to a public API to check if the given passwordhas been compromised in a data breach.
enabled
type:booleandefault:true
If you set this option tofalse, no HTTP requests will be made and the givenpassword will be considered valid. This is useful when you don't want or can'tmake HTTP requests, such as indev andtest environments or incontinuous integration servers.
endpoint
type:stringdefault:null
By default, theNotCompromisedPasswordconstraint uses the public API provided byhaveibeenpwned.com. This optionallows to define a different, but compatible, API endpoint to make the passwordchecks. It's useful for example when the Symfony application is run in anintranet without public access to the internet.
static_method
type:string | arraydefault:['loadValidatorMetadata']
Defines the name of the static method which is called to load the validationmetadata of the class. You can define an array of strings with the names ofseveral methods. In that case, all of them will be called in that order to loadthe metadata.
translation_domain
type:string | falsedefault:validators
The translation domain that is used when translating validation constrainterror messages. Use false to disable translations.
web_link
enabled
type:booleandefault:true orfalse depending on your installation
Adds aLink HTTP header to the response.
webhook
Thewebhook option (and its children) are used to configure the webhooksdefined in your application. Read more about the options in theWebhook documentation.
workflows
type:array
A list of workflows to be created by the framework extension:
12345
# config/packages/workflow.yamlframework:workflows:my_workflow:# ...1234567891011121314151617
<!-- config/packages/workflow.xml --><?xml version="1.0" encoding="UTF-8" ?><containerxmlns="http://symfony.com/schema/dic/services"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:framework="http://symfony.com/schema/dic/symfony"xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"><framework:config><framework:workflows><framework:workflowname="my_workflow"/></framework:workflows><!-- ... --></framework:config></container>123456789
// config/packages/workflow.phpuseSymfony\Config\FrameworkConfig;returnstaticfunction(FrameworkConfig$framework):void{$framework->workflows() ->workflows('my_workflow')// ... ;};See also
See also the article aboutusing workflows in Symfony applications.
enabled
type:booleandefault:false
Whether to enable the support for workflows or not. This setting isautomatically set totrue when one of the child settings is configured.
name
type:prototype
Name of the workflow you want to create.
initial_marking
type:string |array
One of theplaces orempty. If not null and the supported object is notalready initialized via the workflow, this place will be set.
marking_store
type:array
Each marking store can define any of these options:
property(type:stringdefault:marking)service(type:string)type(type:stringallow value:'method')
metadata
type:array
Metadata available for the workflow configuration.Note thatplaces andtransitions can also have their ownmetadata entry.
supports
type:string |array
The FQCN (fully-qualified class name) of the object supported by the workflowconfiguration or an array of FQCN if multiple objects are supported.
support_strategy
type:string
transitions
type:array
Each marking store can define any of these options:
from(type:stringorarray) value from theplaces,multiple values are allowed for bothworkflowandstate_machine;guard(type:string) anExpressionLanguagecompatible expression to block the transition;name(type:string) the name of the transition;to(type:stringorarray) value from theplaces,multiple values are allowed only forworkflow.
type
type:stringpossible values:'workflow' or'state_machine'
Defines the kind of workflow that is going to be created, which can be eithera normal workflow or a state machine. Readthis articleto know their differences.

