Follow these steps to watch an XSS exploit in action:
- Open your favorite text editor, program editor, or integrated development environment (IDE) package.
- Type the following code into the editor window:
<!DOCTYPE html> <html> <head> <title>XSS Test</title> <style> input { margin: 5px; } </style> </head> <body> <h2 id="tab1" >Please enter your first name:</h2> <form action="xsstest.php" method="post"> <input type="text" name="fname"><br> <input type="submit" value="Submit name"> </form> </body> </html>
- Save the file as
xssform.html
in theDocumentRoot
folder for your web server.For XAMPP on Windows, that'sc:\xampp\htdocs
; for XAMPP on macOS, that’s/Applications/XAMPP/htdocs
. - Open a new tab or window in your browser, and type the following code:
<!DOCTYPE html> <html> <head> <title>XSS Test</title> </head> <body> <h1>XSS Test</h1> <?php $fname = $_POST['fname'>; echo "<p>Welcome, $fname</p>\n"; ?> <h2 id="tab2" >This is the end of the test</h2> </body> </html>
- Save the file as
xsstest.php
in theDocumentRoot
folder for your web server. - Open the XAMPP Control Panel, and then start the Apache web server.
- Navigate here.
You may need to change the TCP port used to match your web server.
- In the form, type the following code in the Name text box:
<script>alert("Hello!");</script>
- Click the Submit button to continue.
- Close the browser window when you're done with the test.

The PHP code sent the JavaScript to the browser as part of the echo
statement output, and the browser dutifully ran the JavaScript code. This example is harmless, because it just displays a simple alert message, but a real attacker would embed much more malicious code.
Some browsers, such as Safari and Chrome, have built-in XSS attack detection, which may trigger on this test and block the JavaScript code from running. If you don’t see the alert()
pop-up box, open the developer tools for your browser and see if there's a notice that the browser blocked a potential XSS attempt.
<script>
tag sends the browser to retrieve the JavaScript code file. In the previous example, the JavaScript code was embedded directly within the script element. Remember: The <script>
HTML5 tag can also reference an external JavaScript file, which the browser will load and run. An attacker can specify the src
attribute in the <script>
tag to redirect the browser to run JavaScript located on a rogue server anywhere in the world.There are two different methods of carrying out an XSS attack:
- Reflected attack: The attacker places the rogue script as a link in the submitted data. Victims must actively click the link to launch the XSS attack.
- Persistent attack: The attacker places the rogue script as data that the browser displays when the web page loads (as in the previous example).