PHP and databases
Working with databases in PHP securely – connecting through PDO, prepared statements, defending against SQL injection, storing passwords, protecting forms and login. The examples are verified in PHP 7.4 with MySQL and MariaDB.
PDO is the unified interface for working with databases in PHP. How to connect to MySQL or MariaDB, which options to set right when connecting, where to store the credentials and what to do when the connection fails.
A prepared statement separates the text of a query from the values that go into it. It is the main defense against SQL injection and also the most convenient way to get variables into a query. Selecting, inserting, updating, a list of values in IN, LIMIT and transactions.
SQL injection has long been one of the most dangerous vulnerabilities of web applications. On a specific piece of vulnerable code, we will show how the attack works, why escaping or filtering “dangerous” words does not help and how to fix the vulnerability reliably.
User passwords are never stored in the database as plain text or as a simple MD5 or SHA hash. PHP has ready-made functions for passwords, password_hash and password_verify. How to use them, how big a column to prepare and how to migrate an old website with MD5 passwords.
A CSRF attack exploits the fact that the user is logged in to your website: another website submits a form on their behalf – for example, it deletes an article or changes the e-mail address. How the attack works and how to defend against it with a token in the form.
After login, the session keeps the user on the website logged in – and whoever obtains its identifier is logged in instead of them. How to set up the session cookie, what to do at login and logout and how to limit password guessing.