Table of Contents
Encountering the “Invalid Form Key. Please refresh the page” error in Magento 2 is frustrating, especially if it disrupts admin functionality or customer browsing experience. The error typically arises due to issues in PHP configurations or base URL settings. Here’s how you can address it:
Understanding the “Invalid Form Key. Please refresh the page”
Error
Magento 2 uses form keys as a security measure to prevent Cross-Site Request Forgery (CSRF) attacks. The error is thrown by the system when it is unable to validate a form key during submission. Some of the possible causes are:
- Low max_input_vars Value: The max_input_vars directive in PHP restricts the number of input variables it accepts. A low value can cause Magento to fail to process forms appropriately.
- Incorrect Base URL on Localhost: Utilizing localhost as opposed to 127.0.0.1 may result in cookie and session handling problems.
Solutions
1. Increase max_input_vars in PHP Configuration
Magento 2 often requires a higher max_input_vars value than the default (usually 1000). To adjust this:
- Locate your php.ini file. Common paths include /etc/php/7.x/apache2/php.ini or /etc/php/7.x/fpm/php.ini.
- Open the file and find the line: max_input_vars = 1000.
- Change it to: max_input_vars = 10000.
- Save the file and restart your web server:
- For Apache: sudo systemctl restart apache2
- For Nginx with PHP-FPM: sudo systemctl restart php7.x-fpm and sudo systemctl restart nginx
- For Apache: sudo systemctl restart apache2
This adjustment allows Magento to handle larger forms without triggering the error.
2. Update Base URL to 127.0.0.1
If you are testing on a local environment and your base URL is localhost, Magento might not handle cookies properly. To fix this:
Run the following command in your Magento root directory:
php bin/magento setup:store-config:set --base-url="http://127.0.0.1/"If using HTTPS:
php bin/magento setup:store-config:set --base-url-secure="https://127.0.0.1/"Alternatively, update the base URL directly in the database:
- Access your database using a tool like phpMyAdmin or via command line.
- Locate the core_config_data table.
- Find the entries for web/unsecure/base_url and web/secure/base_url.
- Update their values to http://127.0.0.1/ and https://127.0.0.1/ respectively.
After these changes, clear Magento’s cache:
php bin/magento cache:cleanphp bin/magento cache:flushAdditional Tips
- Clear Browser Cookies: At times, stale cookies may cause session issues. Clearing your browser cookies may be beneficial.
- Disable Custom Modules: If the issue started when you installed a new module, disable it and see if the problem persists.
- Check for Magento Updates: Ensure that you are running the latest version of Magento 2, as updates typically include bug fixes.
By adjusting the max_input_vars setting and configuring the base URL correctly, you can resolve the “Invalid Form Key. Please refresh the page” problem and have a hassle-free Magento 2 experience.