🔴 Advanced  ·  Lesson 35

XSS Prevention

XSS Prevention

What is XSS?

Cross-Site Scripting (XSS) is an attack where a hacker injects JavaScript into your page through input fields. It can steal cookies or deface the site.

How it Happens

// DANGEROUS - directly echoing user input
echo $_GET["name"];
// If name = <script>alert(1)</script>, the script runs!

The Fix: Escape Output

// SAFE - escape before output
echo htmlspecialchars($_GET["name"], ENT_QUOTES, "UTF-8");
// <script> becomes harmless text

Summary

  • XSS injects scripts via user input shown on the page.
  • Always escape output with htmlspecialchars().

XSS क्या है?

Cross-Site Scripting (XSS) एक attack है जहाँ hacker input fields से आपके page में JavaScript inject करता है। यह cookies चुरा सकता है या site बिगाड़ सकता है।

यह कैसे होता है

// DANGEROUS - user input सीधे echo करना
echo $_GET["name"];
// अगर name = <script>alert(1)</script>, script चल जाएगा!

Fix: Output Escape करें

// SAFE - output से पहले escape करें
echo htmlspecialchars($_GET["name"], ENT_QUOTES, "UTF-8");
// <script> harmless text बन जाता है

सारांश

  • XSS page पर दिखाए user input से scripts inject करता है।
  • हमेशा output को htmlspecialchars() से escape करें।
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

Is page ki language (PHP) mein code likhein aur turant chalाएं — yahीं, bina kuch install kiye.
Powered by OneCompiler. Agar editor na khule to yahान naye tab mein kholein.

💻 Live Code Editor

Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें. Agar load na ho to naye tab mein kholें.