How to secure your PHP website: Tips and Best Practices

6 mins
07 Sep 2023

It is common knowledge that almost all websites in the world use the PHP language. When making an application or website, PHP is usually used as the main language. That's because PHP can be called a programming language that is easy to understand and has a large and wide community, so how to secure a PHP website?

However, often the developer ignores security on the website, so irresponsible people can break into the system easily. That's because most of the developers making applications only focus on making them with the hope that the application can run as desired or in accordance with the flow of the system they built without thinking about the security of their system, this is fatal!

Implementation of security on the site is very important, whether it's in the programming language PHP, Ruby, Python, etc. This aims to maintain the system and the trust of your website among users. If an application or website is made with a PHP framework, there is already a security system that has been provided to secure the website system, but unfortunately most developers don't take advantage of this.





1. Use the htmlspecialchars function

To prevent attacks with injection script techniques, it's a good idea to add the htmlspecialchars function to filter characters that are not executed by the browser. Because if you don't filter validation, usually any character can be executed by the browser, and this is very dangerous.

Use this function before executing, for example:


$str = '<script>hello world!</script>';

echo htmlspecialchars($str);

Will generate a string like this:

&lt;script&gt;hello world!&lt;/script&gt;

By using the htmlspecialchars function, any characters related to the script will usually be converted like this:

& (the "and" sign or ampersand) ? &amp;
" (double quote or double quote) ? &quot;
' (single quote or single quote) ? &#039;
< (less than sign or less than) ? &lt;
> (more than sign or greater than) ? &gt;

Usually the most likely place for this to happen is in the contact form, login form, or admin login form.


2. Save the session on IP and use timeout

It is better to use a timeout for every login request that is made, the session is a marker for the server and will disappear when the browser is closed.

To prevent session hijacking, you can save the session ID with a special IP, with the aim of canceling any suspicious requests.


3. Encrypt your data

Digital services do not escape the exchange of data information, for example, when logging in, the backend requires some information to authenticate the information from the user, whether it is suitable or not. This process exchanges data between the backend and frontend. The data encryption process is very necessary to protect data so that unauthorized parties cannot access it. Encryption is needed to change data into irregularities so that the data is not directly known, for example, by encrypting user passwords when registering.

Or, when using an API service, you need authentication when you want to access it. The data encryption process in this case is very necessary so that irresponsible parties cannot find out what information it contains when communicating via HTTP.


4. Hide important files and folders

PHP frameworks like Laravel, Symfony or Codeigniter 4 usually have a good directory structure, but the problem is that not all of these files can be hidden by the browser. Most developers put all the website files into the root folder, in other words, irresponsible people can easily break into important data on your website and insert strange and dangerous codes into your site without you knowing it.

The solution is to move the folder with these important files that are in the root folder to the public server folder, letting the root file contain index.php and the folder contain assets files such as images, javascript, and css. This aims to safely hide important files on your website.

5. Use an SSL certificate and HTTPS

Currently, all browsers such as Chrome, Firefox, and Opera always advise owners to use the https protocol because it is a secure and encrypted protocol for every requests.

SSL strengthens the security of the site and will give search engines confidence that the site is truly safe to use.

6. Use the addslashes function

This function from PHP serves to add the character \ to each quotation mark in the string so that it can prevent attacks from SQL injection. Usually the login form is a vulnerable point against this attack, and you can use the addslashes function to add the characters.

Example usage and output of this function:


$string = addslashes('what is "PHP" language?');


Will produce output like this:

what is \"PHP\" language?

This technique is quite widely used by developers to validate each input request from a login form.


7. Use prepared statements and bind with PDO

Binding parameters in PDO is a technique to increase security when you run queries into SQL with user-derived parameters or other variables. With parameter bindings, you separate the parameter values from the SQL query so that the database will not consider them to be part of the actual SQL command. This is an example of using bind parameters using PDO:

Example of use:


// Use PDO to connect to database
$pdo = new PDO("mysql:host=localhost;dbname=database_name", "username");

// Bind parameters
$username = $_POST['username'];
$stmt = $pdo->prepare("SELECT * FROM user WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

// Get result
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);


8. Securing your website using .htaccess file

The code in .htaccess is used to limit access to a website's folders and manipulate the PHP files that you use. This also applies to setting the directory structure in the URL to be protected.

For example, to manipulate the following portfolio ID url structure: We can change it to

The URL can be changed in the .htaccess code by using the command:

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine on
    RewriteRule ^portfolio/id/(.*) /portfolio.php?id=$1 [L]


9. Using a trusted hosting server providers

Many of the site owners use any type of hosting that is important for cheap prices. Wait a minute. One thing you don't realize is whether the host already has good security and is capable and professional.

Things that look trivial but really have an impact on the application We recommend that you choose a hosting provider that is professional, has a good reputation, and is capable of handling security issues for their users.


10. Implement Auditing & Logging

The application development process really requires logging to monitor how your application is running, without logging, you cannot know if your application is having problems, especially if your web application is large and complicated. Logging is not only used to detect errors on the site, you can also find out how the process flows from the frontend to the backend. You can log in to parts that are vulnerable to attacks, such as login, registration, and payment pages.

By logging and knowing which parts have problems, you can easily audit them.



By carrying out layered security on your web application, of course, it will minimize unwanted things from irresponsible parties. You need to understand that the digital world, including the web, is a transaction of data or information between one computer and another. By applying some of the points that we have made, it is better to do site security and prevention since the development process takes place.