-1

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

DGK.ca
  • 67
  • 6

2 Answers2

1

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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889