← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 11 of 24

PHP Security Best Practices

Security best practices वे locks और habits हैं जो आपकी site को bad guys से safe रखती हैं। इनमें visitors के type किए पर भरोसा न करना और secrets छुपाना शामिल है, दरवाज़े पर कौन है यह खोलने से पहले check करने जैसा।
Syntax
php
$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
<?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";
?>

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
<?php
// Declare `$comment`, set to "<script>alert('xss')</script>"
$comment = "<script>alert('xss')</script>";
// Print `htmlspecialchars($comment)` to the output
echo htmlspecialchars($comment);
?>

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
<?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));
?>

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
<?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";
?>

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
<?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";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. user input concatenate करके SQL बनाना, जो SQL injection की अनुमति देता है।
  2. htmlspecialchars के बिना user input print करना, जो cross-site scripting की अनुमति देता है।
  3. password_hash के बजाय md5 या sha1 से passwords store करना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.