Security Issues

PHP runs on the server, not on the client computer. This means that we have to think carefully about what is being done with information that came from the user.

Cross-Site Scripting

Cross-site scripting occurs when user input on a form is outputted directly to the screen without any further processing. If the user wrote HTML tags in the textbox or textarea, then their HTML would appear on the page. They would also be able to override style rules and write client-side scripts that otherwise affect the output you get. A client-side script can make a call to other resources on the WWW, including server-side programs. This can be quite a problem on a multi-user site.

So, you process the data before you store or use it.

Some functions that are helpful to you in this regard are,


This function takes the string and replaces all 'applicable' characters with their equivalent HTML entities. This means that HTML will be displayed on the screen rather than interpreted by the browser.


This function works a little bit like the previous one. The difference is that it converts a smaller subset of the characters to entities.

SQL Injection


This function is very useful. When you are writing database queries, strings are usually quoted. Sometimes, the information to be stored contains quotation marks or apostrophes that prevent your SQL statements from being interpreted correctly. The slashes that are added to the string make that quotes part of the string rather than the characters that mark its start and end.

If a user entered a single quote in a text field that was being used as part of a database query, they would be able to add a further clause like, OR 1=1. Whatever the first condition was, this OR is going to cause the condition to evaluate to true. If the query were being used to determine whether or not to grant access to the site, this is a massive problem.

General Tips

Think carefully about how your scripts work. If some statements depend on user-supplied information, ensure that you validate it fully. Most potential problems can be dealt with using good validation routines.

Write some scripts and find out how vulnerable they are. Remember that some statements allow multple expressions, even though you might expect to use only one. Write a for loop that where one or more of the expressions contains a variable storing user input. Try to see if you are able to inject a statement into the space where that variable is used. Look up the eval() statement. This is one of the most dangerous statements to use in your own code. If you find a way to inject that into a script from a form, you have a vulnerable script.

Remember that your PHP scripts can have access to file systems, databases and other resources on the server.