[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79QAYBGTW4CZKJ04TAS16M5":3,"skill-same:01M79QAYBGTW4CZKJ04TAS16M5":43},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M79QAYBGTW4CZKJ04TAS16M5","symfony-cheat-sheet",null,"JunMystery\u002FAgent-Guidance","JunMystery","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F161468934?v=4","01M79MTMV8F0BY8NK1A92RA8A0","Jun","01M79MTMWCFBKPHN5B25E6V20B",0,"MIT","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fsymfony-cheat-sheet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# Symfony Cheat Sheet\n\n## Introduction\n\nThis cheat sheet aims to provide developers with security tips when building applications using the Symfony framework.\nIt covers common vulnerabilities and best practices to ensure that your Symfony applications are secure.\n\nWhile Symfony comes with built-in security mechanisms, developers must be aware of potential vulnerabilities and best practices to ensure the applications they build are secure.\nThis guide aims to cover common security issues, emphasizing the importance of understanding Symfony's security features and how to utilize them effectively.\nWhether you're a newcomer to Symfony or an experienced developer looking to reinforce your security practices, this document serves as a valuable resource.\nBy following the guidelines outlined here, you can strengthen the security of your Symfony applications and create a safer digital environment for users and data.\n\n## Main Sections\n\n### Cross-Site Scripting (XSS)\n\nCross-Site Scripting (XSS) is a type of attack where malicious JavaScript code is injected into a displayed variable.\nFor example, if the value of the variable name is `\u003Cscript>alert('hello')\u003C\u002Fscript>`, and we display it in HTML like this: `Hello {{name}}`, the injected script will be executed when the HTML is rendered.\n\nSymfony comes by default with twig templates that automatically protect applications from XSS attacks by using **output escaping** to transform variables containing special characters by wrapping the variable with `{{ }}` statement.\n\n```twig\n\u003Cp>Hello {{name}}\u003C\u002Fp>\n{# if 'name' is '\u003Cscript>alert('hello!')\u003C\u002Fscript>', Twig will output this:\n'\u003Cp>Hello &lt;script&gt;alert(&#39;hello!&#39;)&lt;\u002Fscript&gt;\u003C\u002Fp>' #}\n```\n\nIf you are rendering a variable that is trusted and contains HTML contents, you can use *Twig raw filter* to disable output escaping.\n\n```twig\n\u003Cp>{{ product.title|raw }}\u003C\u002Fp>\n{# if 'product.title' is 'Lorem \u003Cstrong>Ipsum\u003C\u002Fstrong>', Twig will output\nexactly that instead of 'Lorem &lt;strong&gt;Ipsum&lt;\u002Fstrong&gt;' #}\n```\n\nExplore the [Twig output escaping documentation](https:\u002F\u002Ftwig.symfony.com\u002Fdoc\u002F3.x\u002Fapi.html#escaper-extension) to gain insights into disabling output escaping for a specific block or an entire template.\n\nFor other information on XSS prevention that is not specific to Symfony, you may refer to the [Cross Site Scripting Prevention Cheatsheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md).\n\n### Cross-Site Request Forgery (CSRF)\n\nSymfony Form component automatically includes CSRF tokens in the forms, providing built-in protection against CSRF attacks.\nSymfony validates these tokens automatically, eliminating the need for manual intervention to safeguard your application.\n\nBy default the CSRF token is added as a hidden field called `_token`, but this can be customized with other settings on a form-by-form basis:\n\n```php\nuse Symfony\\Component\\Form\\AbstractType;\nuse Symfony\\Component\\OptionsResolver\\OptionsResolver;\n\nclass PostForm extends AbstractType\n{\n\n    public function configureOptions(OptionsResolver $resolver): void\n    {\n        $resolver->setDefaults([\n            \u002F\u002F ... \n            'csrf_protection' => true,  \u002F\u002F enable\u002Fdisable csrf protection for this form\n            'csrf_field_name' => '_csrf_token',\n            'csrf_token_id'   => 'post_item', \u002F\u002F change arbitrary string used to generate\n        ]);\n    }\n\n}\n```\n\nIf you do not use Symfony Forms, follow Symfony's [manual CSRF token generation and validation](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fsecurity\u002Fcsrf.html#generating-and-checking-csrf-tokens-manually). First, install the `symfony\u002Fsecurity-csrf` component:\n\n```bash\ncomposer require symfony\u002Fsecurity-csrf\n```\n\nEnable CSRF protection in `config\u002Fpackages\u002Fframework.yaml`:\n\n```yaml\nframework:\n    csrf_protection: true\n```\n\nNext, consider this HTML Twig template when a CSRF token is generated by the `csrf_token()` Twig function\n\n```twig\n\u003Cform action=\"{{ url('delete_post', { id: post.id }) }}\" method=\"post\">\n    \u003Cinput type=\"hidden\" name=\"token\" value=\"{{ csrf_token('delete-post') }}\">\n    \u003Cbutton type=\"submit\">Delete post\u003C\u002Fbutton>\n\u003C\u002Fform>\n```\n\nConfigure the `delete_post` route to accept `POST`, matching the form. At the start of its controller action, validate the submitted token with the same token ID (`delete-post`) used by Twig. Reject a missing or invalid token before performing any state change:\n\n```php\n$token = $request->request->get('token');\nif (!is_string($token) || !$this->isCsrfTokenValid('delete-post', $token)) {\n    throw $this->createAccessDeniedException('Invalid CSRF token.');\n}\n```\n\nThis illustrative check assumes an `AbstractController` action with a `Request` argument named `$request`. CSRF validation does not authorize deletion: check the caller's permission for the target post separately before deleting it.\n\nYou can find more information about CSRF not related to Symfony in [Cross-Site Request Forgery (CSRF) Cheat Sheet](Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md).\n\n### SQL Injection\n\nSQL Injection is a type of security vulnerability that occurs when an attacker is able to manipulate a SQL query in a way that it can execute arbitrary SQL code.\nThis can allow attackers to view, modify, or delete data in the database, potentially leading to unauthorized access or data loss.\n\nSymfony, particularly when used with Doctrine ORM (Object-Relational Mapping), provides protection against SQL injection through prepared statements parameters.\nThanks to this it is harder to mistakenly write unprotected queries, however, it is still possible.\nThe following example shows **insecure DQL usage**:\n\n```php\nuse Doctrine\\ORM\\EntityManagerInterface;\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\n\nclass ExampleController extends AbstractController {\n    \n    public function getPost(Request $request, EntityManagerInterface $em): Response\n    {\n        $id = $request->query->get('id');\n\n        $dql = \"SELECT p FROM App\\Entity\\Post p WHERE p.id = \" . $id . \";\";\n        $query = $em->createQuery($dql);\n        $post = $query->getSingleResult();\n\n        \u002F\u002F ...\n    }\n}\n\n```\n\nThe examples below show the **correct ways** to provide protection against SQL Injection:\n\n- Using entity repository built-in method\n\n```php\n$id = $request->query->get('id');\n$post = $em->getRepository(Post::class)->findOneBy(['id' => $id]);\n```\n\n- Using Doctrine DQL Language\n\n```php\n$query = $em->createQuery(\"SELECT p FROM App\\Entity\\Post p WHERE p.id = :id\");\n$query->setParameter('id', $id);\n$post = $query->getSingleResult();\n```\n\n- Using DBAL Query Builder\n\n```php\n$qb = $em->createQueryBuilder();\n$post = $qb->select('p')\n            ->from('posts','p')\n            ->where('id = :id')\n            ->setParameter('id', $id)\n            ->getQuery()\n            ->getSingleResult();\n```\n\nFor more information about Doctrine, you can refer to [their documentation](https:\u002F\u002Fwww.doctrine-project.org\u002Findex.html).\nYou may also refer to the [SQL Injection Prevention Cheatsheet](SQL_Injection_Prevention_Cheat_Sheet.md) for more information that is not specific to either Symfony or Doctrine.\n\n### Command Injection\n\nCommand Injection occurs when malicious code is injected into an application system and executed.\nFor more information refer to [Command Injection Defense Cheat Sheet](OS_Command_Injection_Defense_Cheat_Sheet.md).\n\nConsider the following example, where a file is removed using the exec() function without any input escaping:\n\n```php\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpKernel\\Attribute\\AsController;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\n\n#[AsController]\nclass ExampleController \n{\n\n    #[Route('\u002Fremove_file', methods: ['POST'])]\n    public function removeFile(Request $request): Response\n    {\n        $filename =  $request->request->get('filename');\n        exec(sprintf('rm %s', $filename));\n\n        \u002F\u002F ...\n    }\n}\n```\n\nIn the above code, there is no validation of the user's input. Imagine what could happen if the user provides a malicious value like `test.txt && rm -rf .` . To mitigate this risk, it is advisable to use native PHP functions like in this case `unlink()` or Symfony Filesystem Component `remove()` method instead of `exec()`.\n\nFor specific PHP filesystem functions relevant to your case, you can refer to the [PHP documentation](https:\u002F\u002Fwww.php.net\u002Fmanual\u002Fen\u002Frefs.fileprocess.file.php) or [Symfony Filesystem Component documentation](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fcomponents\u002Ffilesystem.html).\n\n### Open Redirection\n\nOpen Redirection is a security flaw that occurs when a web application redirects users to a URL specified in an invalidated parameter. Attackers exploit this vulnerability to redirect users to malicious sites.\n\nIn the provided PHP code snippet:\n\n```php\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpKernel\\Attribute\\MapQueryParameter;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\n\nclass ExampleController extends AbstractController \n{\n\n    #[Route('\u002Fdynamic_redirect', methods: ['GET'])]\n    public function dynamicRedirect(#[MapQueryParameter] string $url): Response \n    {\n        return $this->redirect($url);\n    }\n}\n```\n\nThe controller function redirects users based on the `url` query parameter without proper validation. Attackers can craft malicious URLs, leading unsuspecting users to malicious sites. To prevent open redirection, always validate and sanitize user input before redirection, and avoid using untrusted input directly in redirect functions.\n\n### File Upload Vulnerabilities\n\nFile upload vulnerabilities are security issues that arise when an application does not properly validate and handle file uploads. It's important to ensure that file uploads are handled securely to prevent various types of attacks. Here are some general guidelines to help mitigate this issue in Symfony:\n\n#### Validate file type and size\n\nAlways validate the file type on the server side to ensure that only allowed file types are accepted. See the [Symfony validation documentation](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fvalidation.html).\nAlso, consider limiting the size of uploaded files to prevent denial-of-service attacks and to ensure that your server has enough resources to handle the uploads.\n\nExample with PHP Attributes:\n\n```php\nuse Symfony\\Component\\HttpFoundation\\File\\UploadedFile;\nuse Symfony\\Component\\Validator\\Constraints\\File;\n\nclass UploadDto\n{\n    public function __construct(\n        #[File(\n            maxSize: '1024k',\n            mimeTypes: [\n                'application\u002Fpdf',\n                'application\u002Fx-pdf',\n            ],\n        )]\n        public readonly UploadedFile $file,\n    ){}\n}\n```\n\nExample with Symfony Form:\n\n```php\nuse Symfony\\Component\\Form\\AbstractType;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\FileType;\nuse Symfony\\Component\\Form\\FormBuilderInterface;\nuse Symfony\\Component\\Validator\\Constraints\\File;\n\nclass FileForm extends AbstractType\n{\n    public function buildForm(FormBuilderInterface $builder, array $options)\n    {\n        $builder\n            ->add('file', FileType::class, [\n                'constraints' => [\n                    new File([\n                        'maxSize' => '1024k', \n                        'mimeTypes' => [\n                            'application\u002Fpdf',\n                            'application\u002Fx-pdf',\n                        ],\n                    ]),\n                ],\n            ]);\n    }\n}\n```\n\n#### Use unique filenames\n\nEnsure that each uploaded file has a unique name to prevent overwriting existing files. You can use a combination of a unique identifier and the original filename to generate a unique name.\n\n#### Store uploaded files securely\n\nStore uploaded files outside the public directory to prevent direct access. If you use a public directory to store them, configure your web server to deny access to the upload directory.\n\nRefer to the [File Upload Cheatsheet](File_Upload_Cheat_Sheet.md) to learn more.\n\n### Directory Traversal\n\nA directory or path traversal attack aims to access files and directories that are stored on a server by manipulating input data that reference files with “..\u002F” *dot-dot-slash* sequences and its variations or by using absolute file paths.\nFor more details refer to [OWASP Path Traversal](https:\u002F\u002Fowasp.org\u002Fwww-community\u002Fattacks\u002FPath_Traversal).\n\nYou can protect your application from a directory traversal attack by validating whether the absolute path of the requested file location is correct or strip out the directory information from filename input.\n\n- Resolve the base directory and requested path with [`realpath()`](https:\u002F\u002Fwww.php.net\u002Fmanual\u002Fen\u002Ffunction.realpath.php), rejecting failures. Include the directory separator in the containment check so a sibling such as `\u002Fstorage-private` cannot match `\u002Fstorage`.\n\n```php\nuse Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpKernel\\Attribute\\MapQueryParameter;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\n\nclass ExampleController extends AbstractController \n{\n\n    #[Route('\u002Fdownload', methods: ['GET'])]\n    public function download(#[MapQueryParameter] string $filename): Response \n    {\n        $storagePath = $this->getParameter('kernel.project_dir') . '\u002Fstorage';\n        $filePath = $storagePath . '\u002F' . $filename;\n\n        $realBase = realpath($storagePath);\n        $realPath = realpath($filePath);\n\n        if ($realBase === false || $realPath === false\n            || !str_starts_with($realPath, $realBase . DIRECTORY_SEPARATOR))\n        {\n            throw $this->createNotFoundException();\n        }\n\n        \u002F\u002F Use $realPath for the authorized file operation.\n\n    }\n}\n```\n\nThis illustrative check assumes untrusted users cannot change the directories or symbolic links between validation and file access. Check the caller's permission to access the resolved file separately.\n\n- Strip out directory information with PHP *basename* function\n\n```php\n\u002F\u002F ...\n\n$storagePath = $this->getParameter('kernel.project_dir') . '\u002Fstorage';\n$filePath = $storagePath . '\u002F' . basename($filename);\n\n\u002F\u002F ...\n```\n\n### Dependencies vulnerabilities\n\nDependency vulnerabilities can expose your application to various risks, making it crucial to adopt best practices.\nKeep all Symfony components and third-party libraries up-to-date.\n\nComposer, the dependency manager for PHP makes it easy to update PHP packages:\n\n```bash\ncomposer update\n```\n\nWhen using multiple dependencies, some of them may contain security vulnerabilities.\nTo address this concern, Symfony comes with [Symfony Security Checker](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fsetup.html#checking-security-vulnerabilities). This tool specifically examines the *composer.lock* file in your project to identify any known security vulnerabilities within the dependencies that have been installed and address any potential security issues in your Symfony project.\n\nTo use Security Checker run the following command using [Symfony CLI](https:\u002F\u002Fgithub.com\u002Fsymfony-cli\u002Fsymfony-cli):\n\n```bash\nsymfony check:security\n```\n\n### Cross-Origin Resource Sharing (CORS)\n\nCORS is a security feature implemented in web browsers to control how web applications in one domain can request and interact with resources hosted on other domains.\n\nIn Symfony, you can manage CORS policies using `nelmio\u002Fcors-bundle`. This bundle lets you control CORS rules precisely without changing your server settings.\n\nTo install it with Composer, run:\n\n```bash\ncomposer require nelmio\u002Fcors-bundle\n```\n\nFor Symfony Flex users, the installation generates a basic configuration file in the `config\u002Fpackages` directory automatically. Take a look at the example configuration for routes starting with *\u002FAPI* prefix.\n\n```yaml\n# config\u002Fpackages\u002Fnelmio_cors.yaml\nnelmio_cors:\n    defaults:\n        origin_regex: true\n        allow_origin: ['*']\n        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']\n        allow_headers: ['*']\n        expose_headers: ['Link']\n        max_age: 3600\n    paths:\n        '^\u002Fapi': ~  # ~ means that configurations for this path is inherited from defaults\n```\n\n### Security-related Headers\n\nIt's advisable to enhance the security of your Symfony application by adding to your responses essential security headers as:\n\n- Strict-Transport-Security\n- X-Frame-Options\n- X-Content-Type-Options\n- Content-Security-Policy\n- X-Permitted-Cross-Domain-Policies\n- Referrer-Policy\n- Clear-Site-Data\n- Cross-Origin-Embedder-Policy\n- Cross-Origin-Opener-Policy\n- Cross-Origin-Resource-Policy\n- Cache-Control\n\nTo find more details about individual headers refer to the [OWASP secure headers project](https:\u002F\u002Fowasp.org\u002Fwww-project-secure-headers\u002F).\n\nIn Symfony, you can add those headers either manually or automatically by listening the [ResponseEvent](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Freference\u002Fevents.html#kernel-response) to your to every response or configuring web servers like Nginx or Apache.\n\n```php\nuse Symfony\\Component\\HttpFoundation\\Request;\n\n$response = new Response();\n$response->headers->set('X-Frame-Options', 'SAMEORIGIN');\n```\n\n### Session & Cookies Management\n\nConfigure session cookies under `framework.session` in `config\u002Fpackages\u002Fframework.yaml`. For an HTTPS application, explicitly set [`cookie_secure: true`](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Freference\u002Fconfiguration\u002Fframework.html#cookie-secure); `auto` sets it to `false` for HTTP requests and does not guarantee secure cookies. Keep [`cookie_httponly: true`](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Freference\u002Fconfiguration\u002Fframework.html#cookie-httponly) to prevent JavaScript from reading the cookie.\n\n```yaml\nframework:\n    session:\n        cookie_secure: true\n        cookie_httponly: true\n        cookie_samesite: lax\n```\n\nUse `cookie_samesite: lax`, or `strict` where the application's navigation flows permit it. [SameSite restricts cross-site cookie sending](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FHTTP\u002FReference\u002FHeaders\u002FSet-Cookie#samesitesamesite-value); it does not isolate all origins. For example, sibling subdomains with the same scheme can be [same-site](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FGlossary\u002FSite). Retain CSRF protection for state-changing requests.\n\n[`cookie_lifetime`](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Freference\u002Fconfiguration\u002Fframework.html#cookie-lifetime) is measured in seconds: `5` means five seconds, not five minutes. Cookie expiration does not enforce a server-side session timeout. Implement server-side idle and absolute expiration as described in the [Session Management Cheat Sheet](Session_Management_Cheat_Sheet.md#automatic-session-expiration).\n\n---\nIn Symfony, sessions are managed by the framework itself and rely on Symfony's session handling mechanisms rather than PHP's default session handling via the `session.auto_start = 1` directive in the php.ini file.\nThe `session.auto_start = 1` directive in PHP is used to automatically start a session on each request, bypassing explicit calls to `session_start()`. However, when using Symfony for session management, it's recommended to disable `session.auto_start` to prevent conflicts and unexpected behavior.\n\n### Authentication\n\n[Symfony Security](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fsecurity.html) provides a robust authentication system that includes providers, firewalls, and access controls to ensure a secure and controlled access environment. Authentication settings can be configured in `config\u002Fpackages\u002Fsecurity.yaml`.\n\n- **Providers**\n\n    Symfony authentication relies on providers to fetch user information from various storage types such as databases, LDAP, or custom sources. Providers get users based on the defined property and load the corresponding user object.\n\n    In the example below [Entity User Provider](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fsecurity\u002Fuser_providers.html#security-entity-user-provider) is presented which uses Doctrine to fetch user by unique identifier.\n\n    ```yaml\n    providers:\n        app_user_provider:\n            entity:\n                class: App\\Entity\\User\n                property: email\n    ```\n\n- **Firewalls**\n\n    Symfony uses firewalls to define security configurations for different parts of an application. Each firewall defines a specific set of rules and actions for incoming requests. They protect different sections of the application by specifying which routes or URLs are secured, the authentication mechanisms to use, and how to handle unauthorized access. A firewall can be associated with specific patterns, request methods, access controls, and authentication providers.\n\n    ```yaml\n    firewalls:\n        dev: # disable security on routes used in development env\n            pattern: ^\u002F(_(profiler|wdt)|css|images|js)\u002F\n            security: false\n        admin: # handle authentication in \u002Fadmin pattern routes\n            lazy: true\n            provider: app_user_provider\n            pattern: ^\u002Fadmin\n            custom_authenticator: App\\Security\\AdminAuthenticator\n            logout:\n                path: app_logout\n                target: app_login\n        main: # main firewall that include all remaining routes\n            lazy: true\n            provider: app_user_provider\n    ```\n\n- **Access Control**\n\n    Access control determines which users can access specific parts of an application. These rules consist of path patterns and required roles or permissions. Access control rules are configured under `access_control` key.\n\n    ```yaml\n    access_control:\n        - { path: ^\u002Fadmin, roles: ROLE_ADMIN } # only user with ROLE_ADMIN role is allowed\n        - { path: ^\u002Flogin, roles: PUBLIC_ACCESS } # everyone can access this route\n    ```\n\n### Error Handling Disclosure\n\nSymfony has a robust error-handling system. By default, Symfony applications are configured to display detailed error messages only in the development environment for security reasons. In the production environment, a generic error page is shown. Symfony's error handling system also allows customized error pages based on different HTTP status codes, providing a seamless and branded user experience. Additionally, Symfony logs detailed error information, aiding developers in identifying and resolving issues efficiently.\n\nFor more information about error handling unrelated to Symfony refer to [Error Handling Cheat Sheet](Error_Handling_Cheat_Sheet.md).\n\n### Sensitive data\n\nIn Symfony, the best way to store configurations like API keys, etc., is through the use of environment variables, which are dependent on the application's location.\nTo ensure the security of sensitive values, Symfony provides a *secrets management system* in which values are additionally encoded using cryptographic keys and stored as **secrets**.\n\nConsider an example where an API_KEY is stored as a secret:\n\nTo generate a pair of cryptographic keys you can run the following command. The private key file is highly sensitive and it shouldn't be committed in a repository.\n\n```bash\nbin\u002Fconsole secrets:generate-keys\n```\n\nThis command will generate a file for the API_KEY secret in `config\u002Fsecrets\u002Fenv(dev|prod|etc.)`\n\n```bash\nbin\u002Fconsole secret:set API_KEY\n```\n\nYou can access secret values in your code in the same manner as environment variables.\nIt's very important to note that if there are environment variables and secrets with identical names, **the values from environment variables will always override secrets**.\n\nFor more details refer to [Symfony Secrets Documentation](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fconfiguration\u002Fsecrets.html).\n\n### Summary\n\n- Make sure your app is not in debug mode while in production. To turn off debug mode, set your `APP_ENV` environment variable to `prod`:\n\n    ```ini\n    APP_ENV=prod\n    ```\n\n- Make sure your PHP configuration is secure. You may refer to the [PHP Configuration Cheat Sheet](PHP_Configuration_Cheat_Sheet.md) for more information on secure PHP configuration settings.\n\n- Ensure that the SSL certificate is properly configured in your web server and configure it to enforce HTTPS by redirecting HTTP traffic to HTTPS.\n\n- Implement security headers to enhance the security posture of your application.\n\n- Ensure that file and directory permissions are set correctly to minimize security risks.\n\n- Implement regular backups of your production database and critical files. Have a recovery plan in place to quickly restore your application in case of any issues.\n\n- Use security checkers to scan your dependencies to identify known vulnerabilities.\n\n- Consider setting up monitoring tools and error reporting mechanisms to quickly identify and address issues in your production environment. Explore tools like [Blackfire.io](https:\u002F\u002Fwww.blackfire.io).\n\n## References\n\n- [Symfony CSRF Documentation](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Fsecurity\u002Fcsrf.html)\n- [Symfony Twig Documentation](https:\u002F\u002Fsymfony.com\u002Fdoc\u002Fcurrent\u002Ftemplates.html)\n- [Doctrine Security Documentation](https:\u002F\u002Fwww.doctrine-project.org\u002Fprojects\u002Fdoctrine-dbal\u002Fen\u002F4.5\u002Freference\u002Fsecurity.html)\n",{},"main","5d0a87185c0e172c3901e2a6e5916b6d544b8b94","skills\u002Fsymfony-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance","https:\u002F\u002Fgithub.com\u002FJunMystery","AI is the typist, I am the architect. Building efficient, secure, and user-centric products through disciplined AI prompt engineering.","2026-11-13 17:41:25",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add JunMystery\u002FAgent-Guidance --skill symfony-cheat-sheet",{"tool":35,"command":36},"bunx","bunx skills add JunMystery\u002FAgent-Guidance --skill symfony-cheat-sheet",{"tool":38,"command":39},"pnpm","pnpm dlx skills add JunMystery\u002FAgent-Guidance --skill symfony-cheat-sheet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fsymfony-cheat-sheet\u002FSKILL.md",true,[],[44,50,56,62,68,74],{"skillNo":45,"name":46,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":47,"categories":48,"keywords":49,"publishedAt":18},"01M79QR1E309VJ6CTQKB32AWWA","zero-trust-architecture-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-architecture-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M79QQV7GHYR02DYGN41S23WN","xss-filter-evasion-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxss-filter-evasion-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M79QQNSN7YB8XB61FFSCS3WH","xs-leaks-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxs-leaks-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M79QQHZZJKFDY9132G5A65C2","xpath-injection-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxpath-injection-prevention-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M79QQB9ZSD3DJG8658EHQXR1","xml-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-security-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M79QQ60WKV7PFMXWT9CW8PM6","xml-external-entity-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-external-entity-prevention-cheat-sheet\u002FSKILL.md",[],[]]