How to store code directly in the database? - php

I'm trying to store a line of xml in mysql and after I save it, it gets formatted with some extra characters.
href=\"\" index=\"My Website\" admin=\"Civillage\" default=\"Borak Obama, Mitt Romney\" country=\"USA\" age=\"\" gender=\'\' usertopicsallowed=\'no\' layout=\'line\'
How can I get rid of the backslashes?

just do not add them before saving your text in the database.
check for the magic_quotes setting ant be sure it is turned OFF
check your code for the excessive escaping.
only string data have to be escaped for the query and it has to be done only once.
prepared statements shouldn't be escaped at all

Use stripslashes():
$str = "Is your name O\'reilly?";
echo stripslashes($str); // Outputs: Is your name O'reilly?

Use mysql_real_escape_string($s); on any code input you wish to store in your database, this will escape the characters successfully and not leave you with any superfluous slashes.
For this method to work, a mySQL connection must already be established.
Hope this helps.

Related

Insert strings with apostrophes into database by php

I want to post data into database in safe mode.
For example if i want to add this title to database:
$title = " here is title 'here is title' here is title ";
notice it has apostrophes.
I use this function to make string safe:
function stringsafe($string)
{
$string = strip_tags(trim(addslashes($string)));
return $string;
}
as you see it's adding slashes before apostrophes to make it safe.
I tried to remove slashes when i show the data by stripslashes, it's working but it's has some problems. Is there anyway to post data into database?
On a side note, in fact the general rules of thumb is that, you shouldn't alter user input at all. You should store whatever user input as it is, into your database, so that you can retain user input as original as possible, and only escape it when you need to display or use it.
In your case, yes you are right you have to prevent it from being injected, but you are altering the original input by adding slashes into the original input, which is not very favoured. What if my title contains a string like this <My 21st Birthday Party!> and you stripped it away?
Try using Prepared Statements instead so you can insert any data into your database, without the worries of injection. And only when you need the data to be displayed on a HTML page or console, you escape them accordingly such as htmlentities.

PHP json_encode won't add backslash before french character?

I want to add an element in my json array. Everything is fine until I apply a french character in my input.. (é, à, etc). They're encoded properly, but no backslash are added before the "u00e9"
Here's my code to add a line in the array:
(For this example, the value submited for $_POST['titre'] is "Présidente")
// 1. Get original json from my db
$res=mysql_query("SELECT * FROM produits WHERE p_id=".$id);
$b=mysql_fetch_assoc($res);
// 2. json_decode the result to put in a array
$array_before_json = json_decode($b['p_images'], true);
// 3. Put our submited value in an array
$newImage = array("titre" => $_POST['titre'], "file" => $_FILES['files']['name'][0]);
array_push($array_before_json,$newImage);
$json_encode = json_encode($array_before_json);
// 4. Re-insert array in bd
$res=mysql_query("UPDATE produits SET p_images='".$json_encode."' WHERE p_id=".$id);
Here's now the new json in my database: (4 images)
[{"titre":"Image #2","file":"1149124_65352813.jpg"},{"titre":"Image #3","file":"333047.jpg"},{"titre":"Titre de ma photo","file":"14.jpg"},{"titre":"Pru00e9sidente","file":"16.jpg"}]
As you can see, in the last occurence, the "é" is not properly encoded, it's suppose do have a backslash before the u00e9...
My page is in UTF-8, but I don't know what's the problem...
A backslash in an SQL query has a special meaning. You need to prepare the value to be properly inserted into the query in order to retain all special characters, like backslashes. In your case you need to use mysql_real_escape_string on $json_encode. However, you should be switching to a modern MySQL API that supports prepared statements and use those.
See How can I prevent SQL injection in PHP? and The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
Classic SQL injection. Sort of
Your query looks like:
UPDATE produits SET p_images='blah blah blah Pr\u00e9sidente blah' ...
MySQL doesn't have any special meaning for \u, so the backslash "falls off" uselessly. It it were \n00e9 then you'd get a newline, to give you an idea.
Simple answer: sanitise your input, even if it's from a trusted source (ie. your code - but in this case it's not). Or better still, use PDO - prepared statements will handle this kind of thing for you.

Slashes in text output

From a form, I'm asking the user to enter some text. I will retrieve this text using $_POST['text'].
The user enters the string "It's my text!"
$newText = mysql_real_escape_string($_POST['text']);
Now on the very same page after I've inserted $newText into the database I want to display
the text to the user and also use it as the value of an input text box using PHP.
// I want to make sure the user hasn't added any unsafe html in their string
$newText = htmlentities($newText);
echo "You've entered: " . $newText . "<br />";
echo "<form action=someaction.php method=post>";
echo "<input type=text value=\"" . $newText . "\">";
echo "</form>";
The output is:
You've entered: It\'s my text!
[It\'s my text!]
How do I avoid these slashes, and should I be doing anything else with my data?
You're passing the text through mysql_real_escape_string() which, as the name suggests, escapes the string, including apostrophes. mysql_real_escape_string() is meant only for preparing the data for saving to database. You shouldn't use it when displaying data to the user.
So, the solution is simple: remove the line and use htmlentities() only. Use mysql_real_escape_string() when you're saving the string to database (and only then).
Only use mysql_real_escape_string() on the variable you want to use in the query, because it will add slashes to escape some of the characters in the string. This works great for mysql, but when want to use it on the page it will look weird.
You could make 2 variables, 1 for MySQL and 1 for displaying the raw text.
$text = $_POST['text'];
$db_text = mysql_real_escape($text);
Also note that you should use strip_slashes() on the data you get from the database later, to remove the slashes.
Hope this clear things up a little bit.
Now on the very same page after I've inserted $newText into the database I want to display the text to the user
That's what you are doing wrong.
An HTTP standard require a GET method redirect after every successful POST request.
So, you have to redirect the user on the same page, where you may read inserted data from the database and show it to the user.
As for the mistake you made - just move escaping somewhere closer to the database operations, to make sure it is used only for the purpose (YET it is used obligatory, without the risk of forgetting it!).
Ideally you have to use some variables to represent the data in the query, and some handler to process them.
So, the query call may look like
DB::run("UPDATE table SET text=s:text",$_POST['text']);
where s:text is such a variable (called placeholder), which will be substituted with the $_POST['text'] value, properly prepared according to the type set in the placeholder name (s means "string", tells your function to escape and quote the data)
So, all the necessary preparations will be done inside and will spoil no source variable.
save normally using mysql_real_escape_string()
and when you want to display it in a form:
htmlspecialchars(stripslashes($row['text_data']))
it will do the trick.

stripslashes issue in php

when i use stripslashes in php but i did not get the exact solution. I have menstion below which i used in my code those are
Example if i have the value in table like suresh\'s kuma\"r
i trying to display the value in the following three formats but no one is giving exact value
1) value=<?=stripslashes($row[1])?> //output is suresh's
2) value='<?=stripslashes($row[1])?>' //output is suresh
3) value="<?=stripslashes($row[1])?>" //output is suresh's kuma
But the exact output i need is suresh's kuma"r
let me know how to resolve the this issue?
The issue has nothing do to with stripslashes. If I guess correctly, the problem lies in the fact that in your examples quotes break the html field attribute;
I'll show you by manually echoing out your $row content as per your infos:
value=sures kumar --> leads to browser to interpret this as value="sures" kumar
value='suresh'khumar --> well, same story value='sures' khumar
value="Suresh"Khumar -->what can I say...you know the drill
Escaping the quotes won't affect html, since backslashes has no meaning in html.
Both value="Suresh" and value="Suresh\" will work fine for the browser, but your name will always be interpreted by the browser as some unknown attribute, leaving only the first part inside the value.
What you might do, instead, is apply htmlentities($row[1],ENT_QUOTES) so that they get converted in the equivalent entity (&quote;,for ex.) and not break your value attribute. See manual.
Another issue is that you shouldn't be having backslashes in your database in the first place; this might be due to the presence of magic_quotes enabled in your provider, or you passing manually addslashes() or other wrong trickery. If you want to insert into a database values containing quotes, use the escaping mechanism provided by your database driver (mysql_real_escape_string() in mysql, for ex.), or better tools (preparated statements with query bindings).
You should first get rid of all the slashes using that stripslashes and re-saving back the content; but slashes or not, the issue would appear again if you don't format that appropriately for your html, as I showed above.
Are you sure you want stripslashes instead of addslashes? Is the purpose is to quote the " characters?

SQL injection help

So I was just testing out the mysql_real_escape(); function and what that does is puts a \ before the ". The when the content is echoed back out onto the page I just get content with \'s before any ". So let's say I posted """""""""""""""""""""""""""" all I get is \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" echoed back.
Is there some code to remove the \ when it's echoed back onto the page?
By adding those slashes, mysql_real_escape_string just converts the string into the input format for the database. When the data comes out of the database, it should come out without any of the slashes. You shouldn't need to remove them yourself.
Using stripslashes like others are suggesting would do the opposite of mysql_real_escape_string in most cases, but not all of them, and you shouldn't rely on it for that purpose. Mind you, if you find yourself needing to use it for this, you've already done something else wrong.
stripslashes()
http://php.net/manual/en/function.stripslashes.php
You don't need to unescape, ie. remove the slashes - they don't get inserted into the DB. They are only for passing data to MySQL, they are not written to the db. When you SELECT the data, you won't see the slashes.
Do you know how mysql_real_escape() works. Hint: It allows to encode string for SQL usage. For example mysql_query('SELECT * FROM users WHERE name="'.mysql_real_escape_string($name).'"');. It can be used to insert string which won't escape the quotes for example like " or 1=1 -- " making SELECT * FROM users WHERE name="" or 1=1. You have to activate it just before inserting it database.
When you will read this data, slashes won't exist in any way.
Actually, looking at what is below, I will make this answer, not comment...

Categories