How to protect a website from xss (Cross site scripting) - php

Ok so i've learned a bit of PHP and tried making a simple application but i am not sure is my webpage secure from xss and other such attacks .
My PHP CODE
<?php
$title=$keywords=$description="";
$valid_er="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST['title'])){
$valid_er="has-error";
}
else{
$title="<title>".test($_POST["title"])."<title>";
}
$keywords='<meta name="keywords" content="'.test($_POST["keywords"]).'" />';
$description='<meta name="description" content="'.test($_POST['description']).'" />';
}
function test($ci){
$ci=htmlentities($ci);
$ci=stripcslashes($ci);
return $ci;
}
?>
And MY HTML FORM
<form method='post' class='form-group' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label> Your Title </label> <input placeholder="Your websites title" type="text" name="title" class='form-control' class='form-group-item'/></br>
<label> Keywords </label> <input placeholder="Your keywords separated by comma " type="text" name="keywords" class='form-control' class='form-group-item'/></br>
<label>Description </label> <textarea placeholder="A nice description about your website;" name="description" class='form-control'></textarea></br>
<input type="submit" class='btn btn-info'>
</form>
I just wanted to know am i vulnerable to cross site scripting , because i don't think only using
htmlspecialchars()
will protect me .

I just wanted to know am i vulnerable to cross site scripting
No, you are not, and just using htmlspecialchars will protect you against XSS in most cases (if you use double quotes around attributes and follow the rules in my last paragraph).
You don't need to use stripcslashes, and you don't need to encode your own <, etc.
Do note however that htmlspecialchars does not encode a single quote (') by default. I mention this because for your form tag, you mainly use single quotes, and just double quotes for the action,which is a really good idea, as otherwise your code would be vulnerable to XSS. To avoid this problem, you can use htmlspecialchars($string, ENT_QUOTES, 'UTF-8');, with which single quotes would also be encoded. You still can't just omit using any quotes (if you do that, preventing XSS becomes a lot more complicated, as you would need to escape all characters with which you can break out of that context, which include space, +, etc), but with this, you can use double or single quotes and be safe.
For more information, check out this site about XSS prevention (it tells you where this kind of encoding is not enough; you should never put user input inside <script>, <style>, HTML comments, attribute names, or tag names).

Related

Liquid equivalent of 'htmlspecialchars'

I'm trying to escape the input fields in a standard HTML form while using the Liquid templating engine in Octopress.
<input type="hidden" name="post_title" value="{{page.title}}" />
What is the Ruby/Liquid equivalent to PHP's htmlspecialchars? Is there already a filter that does this, or do I need to use a custom replace?
It seems that the standard escape filter will do the trick.
<input type="hidden" name="post_title" value="{{ page.title | escape }}" />
Although the documentation on the filter is annoyingly non-helpful, checking the code, it uses CGI.escapeHTML which has a much better documentation page and seems to escape the same characters as the PHP equivalent.
Note that it only escapes double quotes, so single quote escaping will need to be done manually if needed.
CGI::escapeHTML("<foo>&&&</foo>")
#=> "<foo>&&&</foo>"

White space issue with PHP

I am accepting a preset input from another .php file
$Instructor=$_POST["Instructor"];
when I echo $Instructor, the OUTPUT is Dr. Doom (which is correct)
When i pass it through a fieldset I only get the (Dr.) and not the (Doom). I need for the entire name to get passed. Can any one please help. I am NEW TO PHP, so please try to explain in simple form. Thank you very much ahead of time.
here is the code i am using.
echo "<fieldset>
<Legend> Contact Information </Legend>
PROFESSOR: <inputname='Professor' type= 'text' value=$Instructor maxlength='35'
disabled='disabled'> </fieldset>"
Sincce you've omitted quotes on HTML attribute, only characters up to the first whitespace will be interpreted in your html. Quote the attribute, and escape it properly with htmlentities() using the ENT_QUOTES option:
echo "<fieldset ... ... value='" . htmlentities($Instructor, ENT_QUOTES) . "' ... </fieldset>";
Note that without the escaping, it is vulnerable to cross-site scripting, in addition to potentially breaking the output markup.
You need to put quotes around attribute values that contain spaces. In your case they need to be escaped, because the PHP string literal also uses them:
echo "... value=\"$Instructor\" ...";
Variable sanitization aside, you forgot to quote this:
value=$Instructor
And mind the space here:
type= 'text'
By the way, There's a nice syntax in PHP called "heredoc" if you want to use blocks of HTML text.
$str = <<<EOF
<fieldset>
<Legend> Contact Information </Legend>
PROFESSOR: <inputname='Professor' type='text' value='$Instructor' maxlength='35' disabled='disabled'>
</fieldset>
EOF;
What's nice is the text can stay human readable and still support inline variable interpolation (putting "$something like this")

Escaped characters in string from submitted form

Every time a POST is made I get escaped characters.
\ -> \\
' -> \'
" -> \"
I have a multistep form, which transmits the data from one form to another. I save the values with prepared statments in the database. The values in the database currently look like Paul\'s House. User should have the possiblity to use single and double quotes in their string.
This is a simple example demonstrating the escaping effect:
<?php
echo $_POST['value'];
?>
<form action="form.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="value" value="Paul's House">
<input type="submit" value="Next">
</form>
Why or who escapes the string? What is the correct way for handling data over multiple forms? What is the correct way for saving it in the database? Should I use stripslashes() or I'm opening a big security hole?
Looks like you have Magic Quotes turned on.
http://www.php.net/manual/en/security.magicquotes.disabling.php
Check that out for how to disable.
You must turn off the magicquotes in server , otherwise you should very careful about on/off status of the magicquotes .

Link is cut off after quotation in php

When I have a form like this one -
<form action="t.php" method="get">
<input type="text" name="test"></input>
<input type="submit"/>
</form>
Processed by PHP like this -
<?php
$t = $_GET["test"];
echo "<a href='".$t."'>".$t."</a>";
?>
If I provide an form input like -
What's a form?
The link is cut off after "What". I know this is because of the quotation mark, but I'm not sure how to get around it in a way that would deal with any number of single or double quotation marks.
Any Ideas? Thanks.
echo "<a href='".urlencode($t)."'>".$t."</a>";
To play safe, you should cater htmlspecialchars to protect yourself from xss or so
htmlspecialchars
echo "<a href='".urlencode(htmlspecialchars($t), ENT_QUOTES))."'>".$t."</a>";
_________________^ cater for question mark which not able to convert
You could also use addslashes() and stripslashes().

Slashes within echo of input type html

I do not want to display all the slashes when displaying the html
What I have is
echo "<input type=\"text\" name=\"myname\" value=\"myvalue\"";
What I want to do is:
echo '<input type="text" name="myname" value="myvalue">';
I am looking to save myself from typing all the slashes. Is there a way around that?
Your second example works (although it is ugly), I assume you want a way to be able to print variables while printing the HTML with double quotes. If that's the case, you could use Heredoc syntax:
echo <<<DOC
<input type="text" name="myname" value="myvalue">
DOC;
Or, better, yet, you could use a templating system (which PHP kind of is) or a MVC framework to separate your business and presentational logic so you don't have to go around printing stuff like input fields in the first place. :)
You probably don't want to echo stuff really, and Paolo explained that quite well, but in general the best practice regarding apostrophes and quotation marks is as follows:
When you have apostrophes ' in the text, enclose it in double quotes "
echo "foo bar 'baz'";
When you have double quotes, enclose in apostrophes
echo 'foo bar "baz"';
This way you don't have to clutter it with backslashes. If you have both kinds, consider heredoc as per Paolo's example, or just stick to the style the rest of the code usually uses.
As to what comes to using apostrophes in HTML instead of double quotes.. While swapping them might be useful when you want to include variables, it would be more beneficial to always keep the same style - always apostrophes, or always double quotes.
You can also use printf (or sprintf), a function which often seems to be forgotten by PHP programmers:
printf('<input type="text" name="myname" value="%s" />', $value);
Your second example works just fine. However, if you want you can use single slashes to quote the HTML, it will still come out valid. This would also allow you to quote variables:
echo "<input type='text' name='myname' value='$value' />";
Do not forget you can also do something along the lines of:
/* PHP CODE */
?>
--- HTML HERE ---
<input type="text" name="myname" value="myvalue">
<?php
/*PHP CODE */
Typically I use the second example with apostrophes.
<?php
echo '<input type="text" name="myname" value="myvalue">';
?>
As Paolo has mentioned, you can also look into an MVC based framework. Which is Model-View-Controller. It is a very nice way to separate your Display Code (Presentation Logic) from your Functional Code (Business Logic).
A good starter MVC Framework is CodeIgniter. Check out their video tutorials to get a good idea of how these frameworks operate. There is somewhat of a learning curve but it will help you out in the long run!
Other Frameworks and Template Systems:
Zend
Smarty
Cake PHP
Best of Luck!
If you have any questions feel free to leave a comment.
echo '<img src="'.$files[$i].'">';

Categories