0

im creating a application connected to a MYSQL Database where user can login or register. In the register class i use OKHTTP3 to register a new user. OKHTTP3 make a request to a php page that execute the query. The response of the page is always the same (code: 200, messagge:"empty" ). Id like to custom the response of the php page like the code and messagge so i can know if the registration was success or not. How can i do it?

As simple as possible please.

My OKHTTP3 request:

String reg_name = username.getText().toString();
            String reg_pass = password.getText().toString();
            String reg_url = "https://collectcards.000webhostapp.com/register.php";

            OkHttpClient client = new OkHttpClient();

            RequestBody formBody = new FormBody.Builder()
                    .add("user_name", reg_name)
                    .add("user_pass", reg_pass)
                    .build();

            Request request = new Request.Builder()
                    .url(reg_url)
                    .post(formBody)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    // Request failed
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    // Handle whatever comes back from the server
                    String res = response.message(); //MESSAGE IS ALWAYS EMPTY, COSE IS ALWAYS 200
                    if(res.equals("OK")) { //ID LIKE TO CUSTOM THE MESSAGGE TO SAY OK WHEN IT GOES WELL AND NOTOK WHEN IT FAIL
                        ok = true;
                        risposta = "Registrazione Avvenuta";
                    }else {
                        risposta = "Registrazione Fallita";
                        ok = false;
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(thisContext, risposta, Toast.LENGTH_LONG).show();
                            if (ok) {
                                Intent myIntent = new Intent(thisContext, mainMenuActivity.class);
                                thisContext.startActivity(myIntent);
                            }else{
                                password.setText("");
                                username.setText("");
                            }
                        }
                    });



                }
            });

My php page:

<?php  

 $connessione = mysqli_connect("localhost", "usr", "psw", "db");

 $user_name = $_POST['user_name']; 

 $user_pass = $_POST['user_pass'];  

 $query =  "INSERT INTO `player` (`username`, `password`, `money`) VALUES ('".$user_name."', '".$user_pass."', '100');";

 $risultato = mysqli_query($connessione, $query);

if($risultato){
 //CUSTOM MESSAGGE
}else{

}

 ?>
Fyruz
  • 75
  • 1
  • 20
  • 2
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST`, `$_GET` or **any** user data directly into a query, it can be very harmful if someone seeks to exploit your mistake. – tadman Sep 19 '17 at 21:51
  • Yes ill use that, thank you :) – Fyruz Sep 19 '17 at 21:58

1 Answers1

1

You can set the code being output with http_response_code();, eg:

http_response_code(500); 

in case of a server error, 400 for bad request, etc. For the body, you should just be able to echo it right there in the body. I'd recommend doing something like json_encode() 'ing an array of data.

And please don't use PHP close tags.

Why would one omit the close tag?

Skrrp
  • 660
  • 7
  • 11
  • You mean something like this: if($risultato){ http_response_code(1); }else{ http_response_code(2); } – Fyruz Sep 19 '17 at 21:53
  • @GianmarcoFerruzzi yes, exactly like that. But your life will be so much easier in the long run if you use [real HTTP response codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). – Skrrp Sep 19 '17 at 21:55
  • And what about the messagge? How can i custom it? – Fyruz Sep 19 '17 at 21:59
  • I've only worked with frameworks - that handle all of the return stuff for me - but I _think_ you just output it from your script. Start with `echo "foo";` to test the transport, then once you know it's working you can put anything you like in there. As I said, I'd recommend outputting a `JSON` encoded array, so you can send data back in an easy to handle format. – Skrrp Sep 19 '17 at 22:03
  • do you know any usefull guide about that? I mean sending data in JSON. I've already used JSON but only receving from a service not sending. Thk :) – Fyruz Sep 20 '17 at 16:33
  • I'm sure there are many guides around but it's all easy enough, especially if you already know how to handle the received messages. To send, just create an array; `$output = ['type' => 'error', 'messages' => ['message one', 'message two']];` then just `json_encode($output);` – Skrrp Sep 20 '17 at 16:39