PHP Strings · Chapter 7.5 · Security & Hashing

PHP Security String Functions
htmlspecialchars · strip_tags · addslashes · md5 · sha1

PHP Security Functions की पूरी जानकारी — XSS attacks से बचाना, HTML tags हटाना, SQL injection prevent करना, और passwords hashing करना।

🛡️ htmlspecialchars() 🏷️ strip_tags() 🔑 addslashes() #️⃣ md5() 🔐 sha1()
🚨

Security Chapter — ध्यान से पढ़ें!

यह functions Web Security के लिए हैं। गलत use से XSS attacks, SQL injection, और data breaches हो सकते हैं। हर function का सही use case समझो — और password hashing के लिए md5/sha1 की जगह password_hash() use करो।

XSShtmlspecialchars से बचाव
32md5 hash length (hex)
40sha1 hash length (hex)
md5/sha1 — passwords नहीं!

📋 इस Article में क्या-क्या है

  1. htmlspecialchars() — XSS Prevention
  2. htmlspecialchars_decode() — Reverse
  3. strip_tags() — HTML हटाना
  4. addslashes() — Escaping
  5. md5() & sha1() — Hashing
  6. Security Best Practices
  7. Complete Security Example
1
htmlspecialchars() — XSS से बचाना
html
esc

htmlspecialchars()

Special HTML characters को HTML entities में convert करता है। User input को HTML में display करते समय XSS (Cross-Site Scripting) attacks से बचाता है।

PHP 4+ XSS Prevention Returns: string
string htmlspecialchars( string $string, int $flags = ENT_QUOTES|ENT_SUBSTITUTE, ?string $encoding = null )
यह characters convert होते हैं:
&&
<&lt;
>&gt;
"&quot;
'&#039;
htmlspecialchars() — XSS ATTACK कैसे काम करता है
<?php
// User ने यह input दिया (malicious)
$userInput = '<script>alert("Hacked!")</script>';

// ❌ Without htmlspecialchars — DANGEROUS!
echo "Hello, " . $userInput;
// Browser script execute करेगा! XSS attack!

// ✅ With htmlspecialchars — SAFE!
echo "Hello, " . htmlspecialchars($userInput);
// Hello, <script>alert("Hacked!")</script>
// Browser text की तरह display करेगा — safe!
?>
htmlspecialchars() — REAL WORLD EXAMPLES
<?php
// 1. Comment display करना — always use!
$comment = $_POST['comment'] ?? '';
echo "<p>" . htmlspecialchars(trim($comment)) . "</p>";

// 2. Form value में — attribute injection से बचाव
$naam = $_POST['naam'] ?? '';
echo '<input value="' . htmlspecialchars($naam, ENT_QUOTES) . '">';

// 3. Helper function बनाना
function h($str) {
  return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
// अब हर जगह h() use करो
echo "<h1>" . h($_GET['title'] ?? '') . "</h1>";
?>
⚠️ Golden Rule: Database से या user input से आई हर value को HTML में display करते समय htmlspecialchars() ज़रूर use करो। यह PHP security का Rule #1 है।

2
htmlspecialchars_decode() — Entities को वापस Convert करना
html
dec

htmlspecialchars_decode()

htmlspecialchars() का उल्टा — HTML entities को वापस characters में convert करता है। Database में stored encoded data को process करने के लिए।

PHP 5.1+ Returns: string Reverse of htmlspecialchars
string htmlspecialchars_decode( string $string, int $flags = ENT_QUOTES|ENT_SUBSTITUTE )
htmlspecialchars_decode() — EXAMPLES
<?php
// htmlspecialchars → encode
$original = '<b>Hello & "World"</b>';
$encoded = htmlspecialchars($original);
echo $encoded;
// &lt;b&gt;Hello &amp; &quot;World&quot;&lt;/b&gt;

// htmlspecialchars_decode → decode back
$decoded = htmlspecialchars_decode($encoded);
echo $decoded;
// <b>Hello & "World"</b> (original back!)

// html_entity_decode — ALL entities decode करता है
echo html_entity_decode("&copy; 2025 &mdash; HindiNotes");
// © 2025 — HindiNotes
?>
htmlspecialchars_decode vs html_entity_decode: htmlspecialchars_decode() सिर्फ 5 special characters decode करता है। html_entity_decode() सभी HTML entities decode करता है जैसे &copy; → ©, &mdash; → —।

3
strip_tags() — HTML Tags हटाना
strip
tags

strip_tags()

String से सभी HTML और PHP tags हटा देता है — सिर्फ text रहता है। Rich text editor input को plain text में convert करने के लिए।

PHP 4+ Returns: string Allows Whitelist
string strip_tags( string $string, array|string|null $allowed_tags = null )
strip_tags() — BASIC EXAMPLES
<?php
$html = "<h1>Hello</h1> <b>PHP</b> <script>alert('xss')</script> World";

// सब tags हटा दो
echo strip_tags($html);
// Hello PHP World

// Whitelist — कुछ tags रहने दो
echo strip_tags($html, '<b><i><p>');
// Hello <b>PHP</b> World (<h1> और <script> removed)

// PHP 8+ — array whitelist
echo strip_tags($html, ['b', 'i', 'p', 'a']);
?>
strip_tags() — REAL WORLD EXAMPLES
<?php
// 1. Blog excerpt — plain text preview
$richText = "<h2>PHP Tutorial</h2><p>PHP is a <b>popular</b> language used for <i>web development</i>.</p>";
$plainText = strip_tags($richText);
$excerpt = substr($plainText, 0, 100) . "...";
echo $excerpt;
// PHP TutorialPHP is a popular language used for web developme...

// 2. Search index बनाना — tags without content
$content = "<p>PHP <b>programming</b> language</p>";
$searchText = strtolower(strip_tags($content));
// "php programming language" — index करो

// 3. Safe rich text — कुछ safe tags रहने दो
$userHtml = $_POST['content'] ?? '';
$safeHtml = strip_tags($userHtml, ['p', 'b', 'i', 'ul', 'li', 'br']);
echo $safeHtml;
?>

✅ strip_tags() use करो जब:

// Plain text excerpt चाहिए
strip_tags($richContent);

// Specific tags allow करने हैं
strip_tags($html, ['b', 'p']);

ℹ️ htmlspecialchars() use करो जब:

// User input HTML में display
htmlspecialchars($userInput);

// Tags remove नहीं, escape करो

4
addslashes() — Quotes को Escape करना
add
slsh

addslashes()

String में single quotes, double quotes, backslashes से पहले backslash add करता है। Historically SQL queries में use होता था — अब PDO prepared statements preferred हैं।

PHP 4+ Returns: string Legacy Function
string addslashes( string $string )
addslashes() & stripslashes() — EXAMPLES
<?php
// addslashes — quotes के पहले \ add करता है
$str = "It's a "great" day";
echo addslashes($str);
// It\'s a \"great\" day

// stripslashes — \ हटा देता है (reverse)
echo stripslashes("It\\'s a day");
// It's a day

// JavaScript में string pass करना
$jsStr = "He said 'Hello' and \"Bye\"";
echo "<script>var msg = '" . addslashes($jsStr) . "';</script>";
?>
⚠️ SQL के लिए addslashes() मत use करो!
SQL injection prevent करने के लिए addslashes() पर्याप्त नहीं है। हमेशा PDO Prepared Statements use करो:

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]); // Safe!

5
md5() & sha1() — String Hashing
hash
()

md5() & sha1()

String का one-way hash बनाता है। md5 → 32 character hex, sha1 → 40 character hex। File integrity check, cache keys, tokens के लिए — लेकिन passwords के लिए नहीं।

PHP 4+ Returns: string ❌ Passwords नहीं!
string md5( string $string, bool $binary = false )
string sha1( string $string, bool $binary = false )
md5()
128 bit

32 char hex output। Fast लेकिन weak। File checksums के लिए।

sha1()
160 bit

40 char hex output। md5 से better। Git commits में use।

sha256()
256 bit

hash("sha256", $str)। Secure। API tokens के लिए।

password_hash()
bcrypt

Passwords के लिए। Salted + slow। Always use this!

md5() & sha1() — EXAMPLES
<?php
// md5 — 32 char hex
echo md5("Hello");
// 8b1a9953c4611296a827abf8c47804d7

// sha1 — 40 char hex
echo sha1("Hello");
// f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0

// Same input = same hash (deterministic)
echo md5("PHP") === md5("PHP") ? "Same" : "Different";
// Same — same input, same output

// Different input = very different hash
echo md5("PHP"); // b52a6c1f9b4e1aaefa38e0e2b99b8e13
echo md5("php"); // 1d78aa5e72a5e2eff15c29ec2a8d4e5a (बिल्कुल अलग!)
?>
md5/sha1 CORRECT USE CASES + Password Hashing
<?php
// ✅ CORRECT uses of md5/sha1:

// 1. File integrity check
$fileHash = md5_file("download.zip");
echo "MD5: " . $fileHash; // Verify file is not corrupted

// 2. Cache key बनाना
$cacheKey = md5("user_" . $userId . "_profile");
// Short, unique, consistent key

// 3. Gravatar image URL
$email = "rahul@gmail.com";
$gravatarHash = md5(strtolower(trim($email)));
$gravatarUrl = "https://www.gravatar.com/avatar/" . $gravatarHash;

// ❌ WRONG — password के लिए md5 मत use करो
// $hash = md5($password); // NEVER DO THIS!

// ✅ CORRECT — password hashing
$password = "mySecurePass123";
$hash = password_hash($password, PASSWORD_BCRYPT);
echo $hash; // $2y$10$... (bcrypt hash)

// ✅ CORRECT — password verify
if (password_verify($password, $hash)) {
  echo "✅ Password correct!";
}
?>
🚨 CRITICAL — Passwords के लिए md5/sha1 कभी मत use करो!
md5 और sha1 बहुत fast हैं — इसीलिए hackers rainbow tables और brute force से crack कर सकते हैं। Password hashing के लिए:
password_hash($pass, PASSWORD_BCRYPT) — store करने के लिए
password_verify($pass, $hash) — verify करने के लिए
या modern PHP में PASSWORD_ARGON2ID भी use कर सकते हो।

6
Security Best Practices — Summary
ThreatFunctionCorrect Use
XSS Attackhtmlspecialchars()User input HTML में display करते समय
Malicious HTMLstrip_tags()Rich text से unwanted tags हटाने
SQL InjectionPDO Prepared Statementsaddslashes() पर्याप्त नहीं — PDO use करो
Password Storagepassword_hash()md5/sha1 नहीं — bcrypt use करो
File Integritymd5_file() / sha1_file()Downloaded files verify करना
Cache Keysmd5()Unique, short keys generate करना
API Tokenshash("sha256", ...)Secure tokens generate करना

7
Combined Example — Secure User Registration
COMBINED — Secure Registration Form Processing
<?php
// Raw form input
$rawNaam = $_POST['naam'] ?? '';
$rawEmail = $_POST['email'] ?? '';
$rawPassword = $_POST['password'] ?? '';
$rawBio = $_POST['bio'] ?? '';

// Step 1: trim — spaces हटाओ
$naam = trim($rawNaam);
$email = strtolower(trim($rawEmail));
$password = trim($rawPassword);
$bio = trim($rawBio);

// Step 2: strip_tags — HTML हटाओ bio से
$bio = strip_tags($bio);

// Step 3: Validate
$errors = [];
if (strlen($naam) < 2) $errors[] = "नाम बहुत छोटा है";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email";
if (strlen($password) < 8) $errors[] = "Password कम से कम 8 chars";

if (empty($errors)) {
  // Step 4: password_hash — secure hashing
  $hashedPass = password_hash($password, PASSWORD_BCRYPT);

  // Step 5: Gravatar hash for profile pic
  $avatarHash = md5($email);

  // Step 6: Database में save (PDO)
  $stmt = $pdo->prepare("INSERT INTO users (naam, email, password, bio) VALUES (?,?,?,?)");
  $stmt->execute([$naam, $email, $hashedPass, $bio]);

  // Step 7: Display — htmlspecialchars
  echo "Welcome, " . htmlspecialchars($naam) . "!";
}
?>
Secure flow: trim → strip_tags → validate → password_hash → PDO insert → htmlspecialchars display

🏆
PHP String Series — Complete! 25 Functions

✅ Chapter 7 — PHP Strings Complete Series

7.1strlen · strtoupper · strtolower · trim · ucwordsBasic
7.2strpos · str_contains · str_replace · substr · explodeSearch
7.3sprintf · number_format · str_pad · str_repeat · nl2brFormat
7.4strrev · str_word_count · wordwrap · chunk_split · str_splitTransform
7.5htmlspecialchars · htmlspecialchars_decode · strip_tags · addslashes · md5/sha1Security

htmlspecialchars() — Rule #1। हर user input display पर use करो।

strip_tags() — HTML हटाना। Whitelist से safe tags रख सकते हो।

addslashes() — Legacy function। SQL के लिए PDO use करो।

md5() / sha1() — Checksums और cache keys के लिए। Passwords के लिए कभी नहीं।

password_hash() — Passwords के लिए हमेशा यही।

🚀 अगला Chapter: Chapter 7 String Series पूरा हो गया! अब Chapter 8: PHP Arrays — Indexed Array, Associative Array, Multidimensional Array, और 25+ Array Functions। PHP का सबसे powerful data structure।