1

I can't find any reason why my scandinavian characters passed to php isn't shown and stored correctly.

When I use my web application, scandinavian characters works correctly with php and database.

If i write message to database from webapp and load it to android app, characters comes correctly.

In android

String message = "Tässä"

try {

    // open a connection to the site
    URL url = new URL("own_url");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();


    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "");
    con.setRequestProperty("Accept-Language", "fi, en-US,fi;q=0.6, en;q=0.5");
    con.setRequestProperty("Accept-Charset", "UTF-8");

    // Send post request
    con.setDoOutput(true);

    String urlParameters = "message=" + message;

In PHP

$message = $_POST['message'];
error_log($message);

error_log shows it like T\xe4ss\xe4

mysqli_set_charset($con, 'utf8');
date_default_timezone_set('UTC');

$sql = "INSERT INTO messages SET message='$message'";
mysqli_query($con, $sql);

In database it is T?ss

EDIT

Changed query generation to prevent SQL-injection, thanks to user2864740 suggestion.

$stmt = $con->prepare("INSERT INTO messages (message) VALUES (?)");
$stmt->bind_param("s", $message);
$stmt->execute();
EspeH
  • 1,308
  • 2
  • 16
  • 34
  • 1
    Problem #1 - using string interpolation, see http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – user2864740 Aug 19 '15 at 08:50
  • `T\xe4ss\xe4` - 00E4 is the unicode point for `ä`; if it were transfered utf-8 encoded something like `c3 a4` should show up somewhere... – VolkerK Aug 19 '15 at 08:56
  • http://stackoverflow.com/questions/279170/utf-8-all-the-way-through – Bogdan Burym Aug 19 '15 at 09:17
  • could you try add_slashes($_POST['message']) then let me know what this line returns – CaffeineShots Aug 19 '15 at 09:38
  • @caffeineshots it is addslashes($_POST['message']); error_log returns T\xe4ss\xe4 and mysql stored T?ss, so no help. And some documentation says, it will do addslash automatically to $_POST – EspeH Aug 19 '15 at 12:29
  • @user2864740 Can you be more specific about using string interpolation? I return values in string from Mysql and show those in list, all characters comes corretly, so I don't understand the point. – EspeH Aug 19 '15 at 12:33

1 Answers1

0

I found solution for my problem, I needed to have urlParameters to be byte[] like this.

String urlParameters = "message=" + message;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

DataOutputStream wr = new DataOutputStream( con.getOutputStream()){};
wr.write( postData );

But there is problem with API lower than 19, with this:

StandardCharsets.UTF_8

Field requires API level 19 (Current min is 14): java.nio.charset.StandardCharsets#UTF_8

EspeH
  • 1,308
  • 2
  • 16
  • 34