Cross-Site Scripting (XSS) is a type of attack where malicious scripts are injected into insecure websites. This script loads on user browsers when they access your website, creating more problems. It is very important to block these kind of attacks to protect your website. In this article, we will look at how to prevent cross-site scripting in PHP/Apache.
What is Cross-Site Scripting
Cross-site scripting (XSS) is when a bot/attacker places malicious script on your website by entering them in your form input elements like textbox or text area. If your website does not have XSS protections, then this script gets saved into your database, and automatically displayed on user’s browsers. Next time when a user visits your site, this script is automatically run on their browser, and it can cause serious issue to one or more users. For example, if the script is meant to steal username/password, it can seriously damage your website’s security. That is why it is important to prevent XSS on your site.
How to Prevent Cross-Site Scripting in PHP/Apache
Here are the steps to prevent cross-site scripting in PHP/Apache.
1. Open Apache Configuration File
Open terminal and run the following command to open Apache configuration file.
$ sudo vi /etc/httpd/conf/httpd.conf
Depending on your Linux system, your Apache configuration file may be alternatively located at any of the following locations:
/etc/apache2/httpd.conf
/etc/apache2/apache2.conf
/etc/httpd/httpd.conf
/etc/httpd/conf/httpd.conf
2. Enable XSS Protection
Add the following line to your server configuration file.
# Add Security Headers <IfModule mod_headers.c> # Protect against XSS attacks Header set X-XSS-Protection "1; mode=block" </IfModule>
In the above code, we first check if mod_headers is installed on your Apache server. It is generally, installed & enabled by default.
Next, we add the response header X-XSS-Protection and set its value to 1. We also set the mode to block that is browser will not render the page if an XSS attack is detected.
3. Restart Apache Server
Restart Apache Server to apply changes.
$ sudo service apache2 restart
In this article, we have learnt how to protect your website from cross-site scripting (XSS). Its solution has to be implemented from server side and not client side. As you can see it is just a matter of setting a response header. Many of web development frameworks already offer XSS protection by default. However, if it is not the case with your system, then you can easily add the above response header in your PHP/Apache site.
Also read:
Shell Script to Replace Text in File
NGINX Block File Extension
How to Deploy React App on NGINX
How to Monitor NGINX Log File using Ngxtop
How to Install Tomcat with NGINX Proxy
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.