Back slashes appearing when data is picked from text-area in php - php

Here's what I am doing,
<?php
if(isset($_POST['submit'])){
$text_area= mysqli_real_escape_string($dbc, strip_tags(trim($_POST['text_area'])));
echo $text_area;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<input type="textarea" name="text_area" style="width:280px;height:90px" id="myTextarea" />
<input type="submit" name="submit" Value="Submit"/>
</form>
But whenever I try to insert something like this: "Hello World" or 'Hello World', it outputs: \"Hello World\" or \'Hello world\'
where am I going wrong?

That's because you using the mysql-real-escape-string function. Use the stripslashes function on your data before displaying it to remove the slashes.

It seems you are outputting the value from the mysqli_real_escape_string method that escapes the string value for a SQL query to avoid SQL Injection. If you simply want to output anything that was inputted into the textarea then you can just purely show the value from the $_POST array but BEWARE if you don't do any checks you can easily fall victim to someone inputting some javascript etc. and have it appear on the page.
So for example to output just the pure text you sent to the server.
trim($_POST['text_area'])
and then you can call mysqli_real_escape_string again while building your query to make the string safe and avoid some common attacks.

You are using mysqli_real_escape_string incorrectly - it serves no purpose here.
Do not use it in this context, and the problem will go away. Use it only when entering data into a database.

Related

Automatic white space insertion?

I have a side project that I am working on on learning php and sql, mixed with some ajax. I have the following code(samples) that inserts specific data into a database :
index.php -
<textarea class="form-control txt" rows='3' name="data[Address]" id="Address" placeholder="Your Address">
<?php echo isset($results['data']['Address']) ? str_replace("<br />","\n", $results['data']['Address']): ''; ?></textarea>
functions.php -
$data['data']['Address'] = str_replace("\n","<br />", $data['data']['Address']);
sql data -
if($id!=NULL && !empty($id)){
$query = "UPDATE test SET address = '$data' WHERE id = $id";}
Here is my question. Data saves fine into the database, and I can read it back from index.php, but when I go to RE-save it, it adds whitespace before the address field(3 tabs worth), so that when I go to read the data again through index.php, it does not show.
How can I get it to NOT save whitespace, or to remove unneeded whitespace?
Looks like you're storing the contents from the Textarea as HTML in Database. You should always store the "real data" from your $_POST to database. (So newlines stay newlines in your database). The escaping will happen just before you send the data to the browser using htmlspecialchars() or htmlentities().
For your concrete problem try following: Output your POST form-data directly into your textarea:
<form action="#" method="POST">
<textarea name="input"><?= htmlspecialchars ($_POST["input"]); ?></textarea>
<button name="submit1" type="submit">Send it</button>
</form>
Your input-data should appear as you typed it. So use htmlspecialchars() instead of random trim()'ing or nl2br()'ing.
Additionally: Be carefull when building your SQL-Query. Make sure to proper escape each user-editable variable before adding it to the statement. See: http://php.net/manual/en/mysqli.real-escape-string.php
Do it this way:
mysql_query ("INSERT INTO xyz ('val') VALUE ('" . mysql_real_escape_string($_POST["input"]). "')");
Or - even better: Make yourself familiar with some modern and much more secure way of database accessing - like using PDO ( http://php.net/manual/en/book.pdo.php )

Where to use strip_tags() and htmlspecialchars()

Is there a difference where I place my strip_tags and htmlspecialchars tag's? I read that Example 2 is better than Example 1.
But I don't understand how that can be the case, aren't these the same thing? I don't know if it also makes a difference that I am setting it back into a $_POST[] variable.
In my case, it's much easier to use Example 1, because no matter where I use $_POST['test'], I know it's safe... while I need to find ever instance that I echo $_POST['test'] and put the tags around it for Example 2.
Is one truly version safer against XSS Leaks?
Example 1:
<?php
$_POST['test'] = htmlspecialchars(strip_tags($_POST['test']));
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?=$_POST['test']?>" />
</form>
?>
Example 2:
<?php
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?=htmlspecialchars(strip_tags($_POST['test']))?>" />
</form>
?>
Both examples are equal (in output).
The problem I can see is that example #1 overwrites the $_POST data.
I would advise against doing so because you cannot restore the original data at a later point in the script (e.g. if you wish to save the data into a database or output it in a non-HTML context).
I somehow misunderstood the question, but this part of my old answer is still applicable.
They are two different functions.
In your case you should only use htmlspecialchars() since this function is meant to escape special HTML characters (<, >, ").
strip_tags() on the contrary strips HTML tags (and some other stuff, see the docs). Do you really want this behavior? I doubt that. Stripping HTML tags differs from escaping them insofar that it really removes the tags. Escaping only "escapes" them so that the browser renders them as normal text.
This part of code prevent XSS perfectly.
<?php
$myVar = htmlspecialchars($_POST['test']);
// other code
<form action="" method="POST">
<input type="hidden" name="test" value="<?php echo $myVar; ?>" />
</form>
?>
I use it like this
$this->message = htmlspecialchars(strip_tags($this->message));
If you have to use $_POST['test'] in multiple spots I would use example 1 since you wont have to process the other functions (strip_tags, htmlspecialchars) over again sanitizing the same data you already have.

How to save this string in PHP?

When I save this string in PHP:
John: "Yes you can".
In my database is saved as:
John: \
How can I save these strings with " ( without deleting " obviously ).
This is my php code:
$titlepost= mysql_real_escape_string($_POST['title']);
$query = "INSERT INTO `titles` (`title`) VALUES ( '".$titlepost."')";
$res = mysql_query($query) or die("Failed".mysql_error() );
echo $titlepost;
output:
John: \\
FORM:
$title = mysql_real_escape_string($_GET['title']);
<form method="post" action="title.php?done=yes" enctype="multipart/form-data">
<input type="text" size="25" name="title" <?php echo "value=\"".$title."\""; ?> >
<input id="starit" name="submit" value="titleit" type="submit" />
</form>
Your problem has nothing to do with PHP or MysQL.
It is as silly as very simple HTML syntax rule.
It is quite obviously that the code
<input value="John: "YES you can>
will show only quoted "John: " part.
To make it correct, one have to encode special symbols in the value
$titlepost = htmlspecialchars($titlepost,ENT_QUOTES);
?>
<input type="text" name="title" value="<?=$titlepost?>">
As for the slashes - it is silly excessive quoting issue. just quote your strings only once and make sure you have magic_quotes_gpc turned off
If you really just get John: \ in your database, it sounds like you are using magic quotes (that causes you do insert backslashes in the database since you are escaping the escaped string) and the column size is way too small (that's why anything after the backslash is missing).
Try this:
if(get_magic_quotes_gpc()) $_POST = array_map('stripslashes', $_POST);
$titlepost = mysql_real_escape_string($_POST['title']);
This ensures that $_POST does not contain any magic-quotes-escaped data which would break after using mysql_real_escape_string.
Try using prepared statements from PDO
http://php.net/manual/en/pdo.prepared-statements.php
The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

PHP Security - $_POST - Injection

Before going live with my website, i made some thoughts about security:
This question is about understanding the Processing in PHP and not strives for a solution in securing the form.
Consider this barebone script which is completely insecure against xss and
sql injections if provided.
<?
if ($_POST['submit']=="1"){
$input = $_POST['input'];
echo "echo the input: ".$input."<br/>";
}
?>
<form action="<? $PHP_SELF;?>" method="POST">
<input type="text" name="input" value="<? echo $_POST['input'];?>"/>
<input type="hidden" name="submit" value="1"/>
<input type="submit" value="submit"/>
</form>
i am wondering why such an injection like this does not work (in the field input):
";unset('index.php');
i am naively thinking the "; would end the echo and than proceed with the code.
Actually i am very happy this does not work but i would like to know why.
In SQL kind of this would actuall work ' OR 1'.
i know to secure this with addslashes or htmlspecialchars but this is not the question. I want to gain an inside of how php works in processing this.
thanks
The content of $_POST array elements are strings. So, whenever you submit ";unset('index.php');" (btw, doesn't unset work on variables?) you actually send that as a string, not as PHP executable code.
Unless you're using eval(), you don't need to fear about php code being evaluated.
Another thing, don't use addslashes() to secure queries, but use your library's dedicated function, such as mysql_real_escape_string() for mysql. Or better use query bindings with prepared statements and parametrized queries.
It would work if you put it through eval(), but otherwise it's just a string like any other.

How do I block HTML in my form input?

So, I have a basic little script that takes input from an HTML form, is processes by PHP and then writes it to a text file in the form of CSS. I've already got some jerkwad trying to drop tables on the server (There is no SQL but I'd like to keep people from trying none the less) Here is the code that I have thus far, can someone help me block potentially bad input via htmlentities or something else?
The HTML Form
<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />
<input type="submit" value="Post It!" />
</form>
</body></html>
The PHP
<html><body>
<?php
$Friendcode = $_POST['Usercode'];
$Username = $_POST['Username'];
echo "You have recorded the following information on the server ". $Username . " " . $Usercode . ".<br />"; echo "Thanks for contributing!";
$output = ".author[href\$=\"$Username\"]:after { \n"
."content: \" ($Usercode)\" !important\n"
."}";
}
$fp = fopen('file.txt', 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>
</body></html>
You can use htmlentities to convert html tags to their html equiv. < etc. Or you can use strp_tags to get rid of all html tags. If you are using sql use mysql_real_escape_string to make sql queries safer
Whenever you include data entered by the user in HTML code, it is always a good idea to first encode the data, by passing it into htmlspecialchars().
Think of it as a decontamination chamber. This will ensure that any of the HTML special chacters, such as "<" and ">" (deadly viruses) are properly escaped (killed) and won't show up in your page as "real" HTML tags (won't make your webpage sick).
Similarly, you must also encode user input when including it in SQL queries. The function that you use for this purpose varies depending on the database that you are using. Because of the dynamic nature of PHP, if you are a including numeric value in a SQL query, you must first check to make sure the variable contains a number by using functions such as is_numeric() and ctype_digit().
I think the best way to block HTML is to allow only the characters you think a username or a user code may have.
For example, limit the input to letters, numbers and underscores and trim the whitespaces in the beginning and the end of the string. This validation will fail whenever HTML code is provided as input.
I would suggest doing this on both client and server side, with a regex. A client-side example can be found here: jQuery remove all HTML tags EXCEPT Anchors
What happen if someone directly type the url of code.php in browser. They will get the Notice of undefined offset.
You should make at least a check if $_POST is not empty.
if(isset($_POST['submit']) && !empty($_POST))
{
//do operation
}
Validate the user name and user code for special characters and what you allow them to enter with PHP sever side
#Zer0mod: I'd use strip_tags to get rid of HTML and mysql_real_escape_string to take care of any potential SQL injections.
Use PHP to convert every symbol to HTML numbers! Head on over to htmlentities() for details about doing so.

Categories