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).
Related
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 )
I want users to have the ability to enter special characters and for it to still submit to the DB.
I have tested using the input: Dave & ' " *, however it doesn't store in the database. If I don't use special characters as per the above and just use Dave, it stores just fine.
I have tried 2 things:
<p class="clearfix">
<label for="name">name</label>
<input class="validate[required]" id="name" name="name" type="text" value="'.esc_attr($_POST['name']).'">
</p>
and
<p class="clearfix">
<label for="name">name</label>
<input class="validate[required]" id="name" name="name" type="text" value="'.htmlspecialchars($_POST['name']).'">
</p>
Neither work.
Database insertion code after payment:
if(strpos($response['body'], 'VERIFIED') !== false && $_POST['payment_status'] == "Completed") {
//Assign IPN Post Values to Local Variables
$comboString = $_POST['txn_id'].$_POST['payment_date'];
$data = explode('~',$_POST['custom']);
$ipn_data = array(
'name' => mysql_real_escape_string($_POST['name']),
'sale_date' => $_POST['payment_date']
);
$ipn_format = array('%s','%s');
if($ipn_business == $paypal_email) {
$wpdb->insert($wpdb->prefix.'orderdata', $ipn_data, $ipn_format);
$ipn_data['currency'] = $_POST['mc_currency'];
$ipn_data['admin_field'] = $_POST['admin_field'];
send_email($ipn_data);
}
} else {
exit("IPN Request Failure");
}
Two very simple rules for this that apply here:
Make strings safe for inserting into a database when, and only when, inserting in to a database
Make strings safe for showing on screen when, and only when, showing on screen.
(Similar rules for adding to XML, adding to URLs / GET paramteters, putting data into email etc - each had a way of handling it.)
So, when instering into a database, use PDO prepared statements or mysqli prepared statements, as this will make the data safe for you. If you can't, then wrap the string in mysql_real_escape_string(). It will NOT change the contents going in (and thus coming out) of the database, just make it safe to enter.
And when displaying on screen, as you have in your second example, use htmlentities() or mysqlspecialchars(). mysqlspecialchars is best if you know how to handle the quotes, but if unsure, use htmlentities.
While I'm at it, I see you're sending an e-mail. Make sure you remove linebreaks and fake boundaries from values that get added to e-mail headers, and remove fake boundaries from the body (line breaks OK). Preferably use a script for email as they are tricky to make spam proof.
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.
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.
I am beginner in web development, I am developing a site that allows user to post various discussions and others comment and reply on it. The problem I am facing is, the user can post almost anything, including code snippets and any other thing which might possible include single quotes, double quotes and even some html content.
When such posts are being posted, it is intervening with the MySQL insert query as the quotes are ending the string and as a result the query is failing. And even when I display the string using php, the string is being interpreted as html by the browser, where as I want it to be interpreted as text. Do I have to parse the input string manually and escape all the special characters? or is there another way?
You need to read up on a few things
SQL Injection - What is SQL Injection and how to prevent it
PHP PDO - Using PHP PDO reduces the risk of injections
htmlentities
The basic premise is this, sanitize all input that is coming in and encode everything that is going out. Don't trust any user input.
If possible, whitelist instead of blacklisting.
EDIT :
I you want to display HTML or other code content in there, users need to mark those areas with the <pre> tag. Or you could use something like a markdown variation for formatting.
Use PDO, prepared statements and bound parameters to insert / update data, eg
$db = new PDO('mysql:host=hostname;dbname=dbname', 'user', 'pass');
$stmt = $db->prepare('INSERT INTO table (col1, col2) VALUES (?, ?)');
$stmt->execute(array('val1', 'val2'));
Edit: Please note, this is a very simplified example
When displaying data, filter it through htmlspecialchars(), eg
<?php echo htmlspecialchars($row['something'], ENT_COMPAT, 'UTF-8') ?>
Update
As noted on your comment to another answer, if you want to maintain indentation and white-space when displaying information in HTML, wrap the content in <pre> tags, eg
<pre><?php echo htmlspecialchars($data, ENT_COMPAT, 'UTF-8') ?></pre>
Look at mysql_real_escape_string and htmlentities functions in PHP manual.
You can also read the Security chapter in PHP manual.
To avoid the breaking of queries in database (which means you're not escaping them, leaving big holes for sql injection) you use mysql_real_escape_string($string) on the value before passing it to the query string, enclosing it in quotes also.
Ex. $value = mysql_real_escape_string($value); // be sure to have an open connection before using this function.
$query = "select * from `table` where value = '".$value."'";
As for displaying in html, you should at least echo htmlentities($string) before outputting it to the browser.
Like echo htmlentities($mystring, ENT_QUOTES)`;
Edit:
To preserve withe spaces, you can use nl2br function (which converts linebrakes to the html equivalen <br />) or go for a little deeper $string = nl2br(str_replace(" ", " ", $string));, but html code would look a bit ugly, at least for me
Reference: htmlentities and mysql_real_escape_string. nl2br
use mysql_real_escape_string. It is a good practice to use this on all user inputs to prevent SQL Injection attacks.