0

I'm trying to send data to a PHP script from C#. The PHP page will insert the posted data to a database but the encoding needs to be UTF-8.

Here is the code from C#:

WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
NameValueCollection data = new NameValueCollection();
string rq = "data here";
rq = Convert.ToBase64String(Encoding.UTF8.GetBytes(rq));
data["q"] = rq;
byte[] buffer=client.UploadValues("url of php file", "POST", data);

Code inside PHP file:

$data = $_POST["q"];
insert_to_database($data);

If data contains characters like é or à they will be inserted as Ä© Ä .....

Cœur
  • 37,241
  • 25
  • 195
  • 267
Th3Wolf
  • 149
  • 1
  • 10
  • Seems like the error is on PHP side, or actually in the way your database connection is set up. PHP isn't good at knowing encoding types. The data you have is already UTF8, but is treated (by PHP and it's conversation with the database) and ANSI/Latin. – GolezTrol Aug 21 '17 at 14:19
  • I think you'll find the answer to your question in [this question](https://stackoverflow.com/questions/4623733/utf-8-problems-php-mysql) – GolezTrol Aug 21 '17 at 14:21
  • if i went to phpmyadmin and insert the data directly with characters like é à they will show correctly – Th3Wolf Aug 21 '17 at 14:21
  • i will check the question thanks (y) – Th3Wolf Aug 21 '17 at 14:22
  • Jup. The database is probably correct, but the *connection to it* isn't. If PHP tells a UTF-8 MySQL database: "Here is some ANSI data", then MySQL will happily convert its contents and treat each byte as a separate character. And by doing that it will double-encode those multi-byte UTF-8 characters making them appear as two (or more) separate characters. – GolezTrol Aug 21 '17 at 14:23
  • @GolezTrol i've found the solution thanks to your efforts – Th3Wolf Aug 21 '17 at 14:30

1 Answers1

0

I've found the solution here.

The connection needs an encoding inside the php file

 $conn = mysql_connect($server, $username, $password);
 mysql_set_charset("UTF8", $conn);
Th3Wolf
  • 149
  • 1
  • 10
  • Good! As a side note: `mysql_connect` and it's family are old. If you have the opportunity, migrate to MySQLi or PDO to make your project more future-proof. See [PHP/MySQL: Choosing an API](http://php.net/manual/en/mysqlinfo.api.choosing.php) – GolezTrol Aug 21 '17 at 14:31
  • i will check that. thanks a lot @GolezTrol – Th3Wolf Aug 21 '17 at 14:32