PHP Security Best Practices
In this page:
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column = ?"); // SQL injection
$stmt->execute([$value]);
echo htmlspecialchars($input); // XSS
$hash = password_hash($password, PASSWORD_DEFAULT);
password_verify($password, $hash);
SQL Injection रोकना
SQL injection तब होता है जब raw user input सीधे एक query string में concatenate हो जाता है; bound parameters वाले prepared statements (PDO के through) query structure को data से separate कर देते हैं, injection को structurally असंभव बनाते हुए।
उदाहरण: Preventing SQL Injection
<?php
// Create a new `PDO` instance with 'sqlite::memory:', stored in `$pdo`
$pdo = new PDO('sqlite::memory:');
$pdo->exec("CREATE TABLE users (id INTEGER, name TEXT)");
// Declare `$stmt`, set to `$pdo->prepare("INSERT INTO users (id, name) VALUES (?, ?)")`
$stmt = $pdo->prepare("INSERT INTO users (id, name) VALUES (?, ?)");
$stmt->execute([1, "Alice"]);
// Print "Injection-proof: data is bound, not concatenated" to the output
echo "Injection-proof: data is bound, not concatenated";
?>
Login to try C/C++/Java/PHP code in the editor
Cross-Site Scripting (XSS) रोकना
Cross-site scripting एक attacker को किसी page में malicious script inject करने देता है जो दूसरे users देखते हैं; htmlspecialchars() किसी भी user-supplied text को echo करने से पहले < और > जैसे characters को safe HTML entities में convert कर देता है।
उदाहरण: Preventing Cross-Site Scripting (XSS)
<?php
// Declare `$comment`, set to "<script>alert('xss')</script>"
$comment = "<script>alert('xss')</script>";
// Print `htmlspecialchars($comment)` to the output
echo htmlspecialchars($comment);
?>
Login to try C/C++/Java/PHP code in the editor
Safe Password Hashing
password_hash() storage से पहले किसी password पर एक strong, salted one-way hash apply करता है, और password_verify() इसके against एक login attempt check करता है -- raw passwords store करना किसी भी circumstances में कभी नहीं होना चाहिए।
उदाहरण: Safe Password Hashing
<?php
// Declare `$hash`, set to `password_hash("secret123", PASSWORD_DEFAULT)`
$hash = password_hash("secret123", PASSWORD_DEFAULT);
// Print a detailed dump (with types) of `password_verify("secret123", $hash)`
var_dump(password_verify("secret123", $hash));
?>
Login to try C/C++/Java/PHP code in the editor
CSRF Attacks रोकना
CSRF एक logged-in user के browser को एक ऐसी request submit करवाने के लिए trick करता है जो उन्होंने कभी intend नहीं की; हर form में एक random, per-session token embed करना और submit पर इसे verify करना दूसरी sites से forged requests को रोकता है।
उदाहरण: Preventing CSRF Attacks
<?php
// Call `session_start()`
session_start();
// Set `$_SESSION['csrf_token']` to `bin2hex(random_bytes(16))`
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));
// Print "Token embedded in form, verified with hash_equals() on submit" to the output
echo "Token embedded in form, verified with hash_equals() on submit";
?>
Login to try C/C++/Java/PHP code in the editor
Inputs को Validate और Sanitize करना
FILTER_SANITIZE_EMAIL या FILTER_VALIDATE_URL जैसे constants के साथ filter_var() आपको हर एक के लिए fragile custom regex लिखने के बजाय common input types साफ और validate करने का एक consistent, tested तरीका देता है।
उदाहरण: Validating and Sanitizing Inputs
<?php
// Declare `$email`, set to "[email protected]"
$email = "[email protected]";
// Print `filter_var($email, FILTER_VALIDATE_EMAIL) ? "Valid" : "Invalid"` to the output
echo filter_var($email, FILTER_VALIDATE_EMAIL) ? "Valid" : "Invalid";
?>
Login to try C/C++/Java/PHP code in the editor
- user input concatenate करके SQL बनाना, जो SQL injection की अनुमति देता है।
htmlspecialcharsके बिना user input print करना, जो cross-site scripting की अनुमति देता है।password_hashके बजायmd5याsha1से passwords store करना।
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser