PHP json_encode won't add backslash before french character? - php

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.

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/MySQL: Strange output issue when echoing variable from MySQL database

I have a MySQL table that contains names and e-mail addresses. The data was originally imported from a .csv file, and it did not originally contain complete e-mail addresses. We had to append the #place.domain to the user's alias.
When the data is sitting in the MySQL table, it looks normal: person#place.domain; however, when I output the content in PHP, I get this: person #place.domain. There's always a space between the person and the #. It doesn't look like that in the MySQL column, nor does it look like that when I copy/paste the data into Notepad, Word, Excel, etc. Furthermore, if I erase the data in the column and manually replace it with person#place.domain, it displays normally in my PHP app. So I'm guessing there's some hidden character that PHP is picking up that I can't detect. Is there a way for me to clean this up? I've tried TRIM(), REPLACE,(), etc., all to no avail.
UPDATE: I've discovered that, when I click in the MySQL field and move among the characters using my arrow keys, I have to hit the arrow key TWICE to move past the # symbol, yet there is no visible space.
I made this sample code for you:
<?php
$test = "user #mail.com";
$aux = explode("#",$test);
$mailok = trim($aux[0])."#".trim($aux[1]);
echo $test." vs ".$mailok;
?>
This is likely something like non-breaking space (ascii 160). To get rid of it:
UPDATE my_table SET e_mail = REPLACE(e_mail, CHAR(160), '');
Try with a foreach cycle, and do the chr($char) function to every character in the string, it will display you the ascii code of each character in the string, and you will find the wrong character. It's the only solution I found. Hope to be useful

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...

Mysql insert from XML with "hyphen" in field name

I am trying to insert into mysql from an xml using PHP, but the field name contains a "hyphen" and for some reason it is not inserting this field, the rest are fine. I have tried using the hex codes x002D, x2010,x2012, and none have worked. As you can see in my xml, the hyphen is not being changed like the space, but if I just remove the x002D inserts everything after the "E" in other words just inserts -mail_x0020_Address.
This is my xml:
<encuestas>
<ID>9949</ID>
<E-mail_x0020_Address>email#email.com</E-mail_x0020_Address>
<ZIP_x002F_Postal_x0020_Code>90001</ZIP_x002F_Postal_x0020_Code>
</encuestas>
This is my insert statement ( I removed fields, I have 20 on that xml):
"INSERT INTO New_Encuestas_Datos(ID,`email`,`Zip/Postal Code`) VALUES('$product->ID','$product->E-mail_x0020_Address','$product->ZIP_x002F_Postal_x0020_Code')";
The variables are coming from an array reading the xml and like I said, everything is imported except email. I have tried the following combinations:
E-mail_x0020_Address
E_x002D_mail_x0020_Address
E_x2010_mail_x0020_Address
E_x2012_mail_x0020_Address
Can anyone point me what I am doing wrong? Thanks !
Hmm, I doubt you can use it in a string, but in plain PHP it is $product->{'E-mail_x0020_Address'};. But that doesn't matter anyway, as you should escape you values prior to sending them to a database you can nicely name an escaped variable as you like.
Try using:
"INSERT INTO New_Encuestas_Datos(ID,`email`,`Zip/Postal Code`) VALUES('{$product->ID}', '{$product->E-mail_x0020_Address}', '{$product->ZIP_x002F_Postal_x0020_Code}')";
Edited:
Just found here Validate class/method names with regex that '-' is not valid in method names.

Categories