Basic
Advanced
Examples
PHP 8 - Security
Last modified: April 02, 20221. SQL Injection
Ask user to enter text in textbox of a form
Problem
txtUserName = getRequestString("Username");
txtPassword = getRequestString("Password");
txtSQL = "SELECT * FROM Users WHERE Username = " + txtUserName + " AND Password = " + txtPassword
SELECT * FROM Users WHERE Username = 'kafle' AND Password = 'P@ssw0rd'; DROP TABLE Users;
Once the sql is executed, it will delete the Users table
How to prevent it?
txtUserName = getRequestString("Username");
txtPassword = getRequestString("Password");
txtSQL = "SELECT * FROM Users WHERE Username = @0 AND Password = @1";
db.Execute(txtSQL,txtUserName,txtPassword);
2. Cross-site scripting
This happen when a user input JavaScript code in textbox of Form. It allow harmful JavaScript to execute.
Problem. This JavaScript execute
<?php
$user_input = "<script>alert('Your site sucks!');</script>";
echo $user_input;
?>
How to prevent it?
- Secure the application from such attacks using strip_tags function.
<?php
$user_input = "<script>alert('Your site sucks!');</script>";
echo strip_tags($user_input);
?>
- Secure the application from such attacks using filter_var function.
<?php
$user_input = "<script>alert('Your site sucks!');</script>";
echo filter_var($user_input, FILTER_SANITIZE_STRIPPED);
?>
3. Encryption
The code below shows the implementation of md5 and sha1 and can be used for encrypting the password
<?php
echo "MD5 Hash: " . md5("password");
echo "SHA1 Hash: " . sha1("password");
?>