Security

7 questions found

What is SQL injection, and how does using prepared statements with PDO help prevent this common vulnerability in PHP applications?

Beginner
SQL injection happens when untrusted user input is inserted directly into a SQL query string, allowing an attacker to manipulate the query itself and potentially read, modify, or delete data they should never have access to, and prepared statements prevent this by sending the query structure and the user supplied values to the database separately, so the values are always treated as plain data and never as part of the executable query, no matter what characters they contain.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
Real-world example A login form uses a prepared statement to check a submitted email address against the database, ensuring that even if an attacker types something like a quote followed by SQL commands into the email field, it is safely treated as a literal string rather than being executed as part of the query.

Common follow-ups: What other types of injection attacks exist besides SQL injection?;Can prepared statements alone fully protect an application from every security risk?

PDO & Databases;Form Handling & Validation

What is cross site scripting, commonly called XSS, and how does properly escaping output help prevent it?

Beginner
Cross site scripting occurs when an attacker manages to inject malicious script code into a web page that is then executed in another user's browser, often by submitting that script as input somewhere that later gets displayed back to other visitors without being properly escaped, and escaping output using a function like htmlspecialchars before displaying any user supplied data ensures that special characters are converted into their safe text equivalents, so the browser renders the input as plain text rather than executing it as code.
echo htmlspecialchars($userComment, ENT_QUOTES, 'UTF-8');
Real-world example A comment section on a blog escapes every submitted comment before displaying it, ensuring that if a visitor submits a comment containing script tags, it appears harmlessly as plain text to other readers instead of actually running in their browsers.

Common follow-ups: What is the difference between stored and reflected cross site scripting?;Are there any situations where escaping output is not enough to prevent an attack?

Form Handling & Validation;Sessions & Cookies

Why should passwords always be hashed before storing them in a database, and how does PHP's password_hash function make this straightforward and secure?

Intermediate
Passwords must never be stored as plain text because if a database is ever breached, plain text passwords would immediately expose every user's actual password, whereas a properly hashed password uses a one way cryptographic function that cannot be reversed, so even if an attacker gains access to the hashed values, they cannot easily recover the original passwords, and PHP's password_hash function automatically handles generating a secure random salt and uses a strong, regularly updated hashing algorithm by default, removing the need to implement this security sensitive logic yourself.
$hashed = password_hash($plainPassword, PASSWORD_DEFAULT);

if (password_verify($inputPassword, $hashed)) {
    echo 'Login successful';
}
Real-world example A user registration system hashes every new password with password_hash before saving it, and later verifies login attempts with password_verify, ensuring the actual plain text password is never stored anywhere in the database.

Common follow-ups: Why is a plain MD5 or SHA1 hash not considered secure enough for storing passwords today?;What does the PASSWORD_DEFAULT constant actually represent, and can it change over time?

Sessions & Cookies;Basics & Types

What is cross site request forgery, commonly called CSRF, and how do CSRF tokens help protect forms from this type of attack?

Intermediate
Cross site request forgery tricks a logged in user's browser into unknowingly submitting a request to an application they are authenticated with, such as changing their account settings or making a purchase, often by embedding a hidden form or link on a malicious page, and a CSRF token defends against this by including a unique, unpredictable value in every legitimate form that the server generated and remembers, then rejecting any submitted request that does not include that exact matching token, since an attacker's malicious page would have no way of knowing what that token's value actually is.
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

// On submission
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die('Invalid request');
}
Real-world example A banking application includes a unique CSRF token in its funds transfer form, ensuring that even if an attacker tricks a logged in user into visiting a malicious page that attempts to auto submit a transfer request, the request is rejected because it lacks the correct token value.

Common follow-ups: How often should a CSRF token be regenerated?;Do frameworks like Laravel handle CSRF protection automatically for you?

Form Handling & Validation;Sessions & Cookies

Why is validating and sanitizing file uploads important, and what specific checks should you perform to prevent an attacker from uploading a malicious file?

Intermediate
Allowing users to upload files introduces significant security risk if not carefully validated, since an attacker could attempt to upload a disguised executable script rather than the expected file type, and important checks include verifying the actual file content and its true MIME type rather than trusting the filename extension alone, enforcing a strict maximum file size, generating a new random filename rather than using the user supplied one, and storing uploaded files outside of any directory where PHP scripts could be directly executed.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['photo']['tmp_name']);

if (!in_array($mime, ['image/jpeg', 'image/png'])) {
    die('Invalid file type');
}
Real-world example A profile picture upload feature checks the actual MIME type of every uploaded file using finfo rather than trusting its extension, preventing an attacker from renaming a malicious script file with a fake dot jpg extension and having it accepted as a legitimate image.

Common follow-ups: Why is checking a file's extension alone not sufficient to confirm its actual type?;What additional risks exist if uploaded files are stored within a publicly accessible, script executable directory?

File Upload Handling;Form Handling & Validation

What is the principle of least privilege, and how should it guide decisions about database user permissions and environment configuration in a PHP application?

Advanced
The principle of least privilege means every part of a system should only be granted the minimum level of access it genuinely needs to perform its job, and applying this to a PHP application means the database user your application connects with should only have permissions for the specific operations it actually performs, such as select, insert, and update, rather than being granted full administrative rights, and sensitive configuration like database credentials and API keys should be kept outside of publicly accessible files, loaded instead from environment variables or a properly protected configuration file.
// .env file, kept outside the public web root and out of version control
DB_USER=app_readonly
DB_PASS=securepassword
Real-world example A reporting feature that only ever reads data connects to the database using a dedicated read only database user, ensuring that even if that specific part of the application were somehow compromised, an attacker still could not modify or delete any actual data.

Common follow-ups: What other parts of a typical PHP application benefit from applying the least privilege principle?;How should secrets like API keys be managed differently between development and production environments?

PDO & Databases;Deployment & Hosting for PHP Applications

How can PHP's built in disabled functions setting and other server level configuration hardening reduce the impact of a successful attack against an application?

Advanced
Beyond writing secure application code, hardening the PHP environment itself provides an important additional layer of defense, and this includes disabling dangerous functions that are rarely needed in a typical web application, such as exec, shell_exec, and eval, through the disable_functions setting in php.ini, turning off the display of detailed error messages in production so internal application details are never exposed to visitors, keeping PHP and all installed packages updated to receive security patches, and running the web server process with a restricted, non administrative user account.
; php.ini
disable_functions = exec,shell_exec,system,passthru,eval
display_errors = Off
log_errors = On
Real-world example A shared hosting provider disables several potentially dangerous PHP functions across all hosted applications, significantly reducing what an attacker could actually accomplish even if they somehow managed to get malicious code to execute on the server.

Common follow-ups: What is the tradeoff of disabling functions that some legitimate applications might actually need?;How does keeping detailed error messages hidden in production actually improve security?

Deployment & Hosting for PHP Applications;Error & Exception Handling