duanheye7423 2019-05-05 09:05
浏览 53

在PHP文件上使用PDO后,Android共享偏好不起作用

I'm creating an Android app where users can register and login.

At the moment registration and login work perfectly.

But the PHP code is vulnerable to SQL Injection attacks and so I want to make it secure using PDO.

When a user registers, his Name and Surname is saved in the Shared Preferences and he shows it in his Home activity.

The problem is that when I use the Login script with PDO the variables in the SharedPreferences are wrong's.

If I have 10 users, it shows me the name and surname of a user 1, even if I log in with user 2, user 3, user 4 etc ...

Moreover if I use the Register.php file with PDO, it doesn't save me at all users's name and surname in SharedPreferences.

So I want to understand why the SharedPrefrences don't work after my PHP file changes?

What am I wrong with the PHP file with PDO?

Does anyone have any advice for me?

I listen to you willingly.

Login.php Without PDO

<?php

   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
       include_once("config2.php");

    $idAKr = $_POST['idAKr'];
    $cell = $_POST['cellulare'];

     if( $idAKr == '' || $cell == '' ){
            echo json_encode(array( "statusr" => "false","message" => "Inserisci numero di telefono!") );
     }else{
        $query= "SELECT * FROM Ristoratori WHERE cellulare='$cell'";
            $result= mysqli_query($con, $query);

            if(mysqli_num_rows($result) > 0){  
             $query= "SELECT * FROM Ristoratori WHERE cellulare='$cell'";
                         $result= mysqli_query($con, $query);
                     $emparray = array();
                         if(mysqli_num_rows($result) > 0){  
                         while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
                         }
               echo json_encode(array( "statusr" => "truer","message" => "Accesso eseguito", "datar" => $emparray) );
            }else{ 
                echo json_encode(array( "statusr" => "false","message" => "Numero di telefono sbagliato!") );
            }
             mysqli_close($con);
     }
    } else{
            echo json_encode(array( "statusr" => "false","message" => "Errore, riprova!") );
    }
?>

Login.php with PDO

<?php

   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
$output = array();

require_once('db.php');

    $idAKr = $_POST['idAKr'];
    $cell = $_POST['cellulare'];

     if( $idAKr == '' || $cell == '' ){
            echo json_encode(array( "statusr" => "false","message" => "Inserisci numero di telefono!") );
     }else{

         $conn=$dbh->prepare("SELECT * FROM Ristoratori WHERE cellulare=?");
         $conn->bindParam(1,$cell);
         $conn->execute();


            if($conn->rowCount() !==0){
             $query= "SELECT * FROM Ristoratori WHERE cellulare='$cell'";
                         $result= mysqli_query($con, $query);
                     $emparray = array();
                         if(mysqli_num_rows($result) > 0){  
                         while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
                         }
               echo json_encode(array( "statusr" => "truer","message" => "Accesso eseguito", "datar" => $emparray) );
            }else{ 
                echo json_encode(array( "statusr" => "false","message" => "Numero di telefono sbagliato!") );
            }
     }
    } else{
            echo json_encode(array( "statusr" => "false","message" => "Errore, riprova!") );
    }
?>

Register.php without PDP

<?php


   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
       include_once("config2.php");

    $idAKr = $_POST['idAKr'];
    $cell = $_POST['cellulare'];
    $nome = $_POST['nome'];
    $cognome = $_POST['cognome'];
    $data = $_POST['data_nascita'];
    $sesso = $_POST['sesso'];
    $ristorante = $_POST['ristorante'];

   // $data_iscrizione = $_POST['data_iscrizione'];
  //  $data_scadenza = $_POST['data_scadenza'];
$data_iscrizione = date('Y/m/d');
$data_scadenza = date_create_from_format('Y/m/d', $data_iscrizione)->add(new DateInterval('P6M'))->format('Y/m/d');

    $fk_id_ristorante = $_POST['fk_id_ristorante'];

     if($nome == '' || $cognome == '' || $data == '' || $ristorante =='' ){
            echo json_encode(array( "statusr" => "false","message" => "Inserisci tutti i dati") );
     }else {

            $query= "SELECT * FROM Ristoratori WHERE ristorante='$ristorante'";
            $result= mysqli_query($con, $query);



            if(mysqli_num_rows($result) > 0){  
               echo json_encode(array( "statusr" => "false","message" => "Nome Ristorante già in uso") );
            }else{ 
             $query = "INSERT INTO Ristoratori (idAKr,cellulare,nome,cognome,data_nascita,sesso,ristorante,FK_id_ristorante) VALUES ('$idAKr','$cell','$nome','$cognome','$data','$sesso','$ristorante','$fk_id_ristorante')";


             if(mysqli_query($con,$query)){

                 $query= "SELECT * FROM Ristoratori WHERE nome='$nome' AND cognome='$cognome' AND data_nascita='$data' AND ristorante='$ristorante' ";
                         $result= mysqli_query($con, $query);
                     $emparray = array();
                         if(mysqli_num_rows($result) > 0){  
                         while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
                         }

             echo json_encode(array( "statusr" => "truer","message" => "Registrazione completata!" , "datar" => $emparray) );
             }else{
                 echo json_encode(array( "statusr" => "false","message" => "Errore5") );
            }
            //prova

        }
                mysqli_close($con);
     }
     } else{
            echo json_encode(array( "statusr" => "false","message" => "Errore3") );
    }

 ?>

Register.php with PDO

<?php


   if($_SERVER['REQUEST_METHOD']=='POST'){
  // echo $_SERVER["DOCUMENT_ROOT"];  // /home1/demonuts/public_html
//including the database connection file
$output = array();


require_once('db.php');

    $idAKr = $_POST['idAKr'];
    $cell = $_POST['cellulare'];
    $nome = $_POST['nome'];
    $cognome = $_POST['cognome'];
    $data = $_POST['data_nascita'];
    $sesso = $_POST['sesso'];
    $ristorante = $_POST['ristorante'];

   // $data_iscrizione = $_POST['data_iscrizione'];
  //  $data_scadenza = $_POST['data_scadenza'];
$data_iscrizione = date('Y/m/d');
$data_scadenza = date_create_from_format('Y/m/d', $data_iscrizione)->add(new DateInterval('P6M'))->format('Y/m/d');

    $fk_id_ristorante = $_POST['fk_id_ristorante'];

     if($nome == '' || $cognome == '' || $data == '' || $ristorante =='' ){
            echo json_encode(array( "statusr" => "false","message" => "Inserisci tutti i dati") );
     }else {
         $conn=$dbh->prepare("SELECT ristorante FROM Ristoratori WHERE ristorante=?");
         $conn->bindParam(1,$ristorante);
         $conn->execute();




         if($conn->rowCount() !==0){
               echo json_encode(array( "statusr" => "false","message" => "Nome Ristorante già in uso") );
            }else{ 
                $conn=$dbh->prepare('INSERT INTO Ristoratori(idAKr,cellulare,nome,cognome,data_nascita,sesso,ristorante,FK_id_ristorante) VALUES (?,?,?,?,?,?,?,?)');
                //encrypting the password
                $conn->bindParam(1,$idAKr);
                $conn->bindParam(2,$cell);
                $conn->bindParam(3,$nome);
                $conn->bindParam(4,$cognome);
                $conn->bindParam(5,$data);
                $conn->bindParam(6,$sesso);
                $conn->bindParam(7,$ristorante);
                $conn->bindParam(8,$fk_id_ristorante);

                $conn->execute();

             if($conn->rowCount() !==0){

                 $query= "SELECT * FROM Ristoratori WHERE nome='$nome' AND cognome='$cognome' AND data_nascita='$data' AND ristorante='$ristorante' ";
                         $result= mysqli_query($conn, $query);
                     $emparray = array();
                         if(mysqli_num_rows($result) > 0){  
                         while ($row = mysqli_fetch_assoc($result)) {
                                     $emparray[] = $row;
                                   }
                         }

             echo json_encode(array( "statusr" => "truer","message" => "Registrazione completata!" , "datar" => $emparray) );
             }else{
                 echo json_encode(array( "statusr" => "false","message" => "Errore5") );
            }

        }

     }
     } else{
            echo json_encode(array( "statusr" => "false","message" => "Errore3") );
    }

 ?>

Register.java

  private void registerRistoratore() throws IOException, JSONException {

        if (!AndyUtilsRistoratore.isNetworkAvailableRistoratore(r_register.this)) {
            Toast.makeText(r_register.this, "Internet is required!", Toast.LENGTH_SHORT).show();
            return;
        }
        AndyUtilsRistoratore.showSimpleProgressDialogRistoratore(r_register.this);
        final HashMap<String, String> mapRistoratore = new HashMap<>();
        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.IDRistoratore, etidAKr.getText().toString());
        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.CELLRistoratore, etcellulare.getText().toString());
        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.NOMERistoratore, etnome.getText().toString());
        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.COGNOMERistoratore, etcognome.getText().toString());
        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.DATARistoratore, etdata.getText().toString());
        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.RISTORANTEmono, etristorante.getText().toString());

        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.SESSORistoratore, ((RadioButton) findViewById(rGroup.getCheckedRadioButtonId())).getText().toString());

       // mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.DATAIscrizione, data_iscrizione.getText().toString());
     //   mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.DATAScadenza, data_scadenza.getText().toString());
        mapRistoratore.put(AndyConstantsRistoratore.ParamsRistoratore.FKIDRistorante, fk_id_ristorante.getText().toString());



        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] paramsRistoratore) {
                String responseRistoratore="";
                try {
                    HttpRequestRistoratore reqRistoratore = new HttpRequestRistoratore(AndyConstantsRistoratore.ServiceTypeRistoratore.REGISTERRistoratore);
                    responseRistoratore = reqRistoratore.prepareRistoratore(HttpRequestRistoratore.Method.POST).withDataRistoratore(mapRistoratore).sendAndReadStringRistoratore();
                } catch (Exception eRistoratore) {
                    responseRistoratore=eRistoratore.getMessage();
                }
                return responseRistoratore;
            }
            protected void onPostExecute(String resultRistoratore) {
                //do something with response
                Log.d("newwwss", resultRistoratore);
                onTaskCompletedRistoratore(resultRistoratore, RegTaskRistoratore);
            }
        }.execute();
    }


    private void onTaskCompletedRistoratore(String responseRistoratore,int taskRistoratore) {
        Log.d("responsejson", responseRistoratore);
        AndyUtilsRistoratore.removeSimpleProgressDialogRistoratore();  //will remove progress dialog
        switch (taskRistoratore) {
            case RegTaskRistoratore:

                if (parseContentRistoratore.isSuccessRistoratore(responseRistoratore)) {

                    parseContentRistoratore.saveInfoRistoratore(responseRistoratore);
                    Toast.makeText(r_register.this, "Registrazione completata!", Toast.LENGTH_SHORT).show();
                    Intent intentRistoratore = new Intent(r_register.this,OnBoardingR.class);
                    intentRistoratore.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intentRistoratore);
                    this.finish();

                }else {
                    Toast.makeText(r_register.this, parseContentRistoratore.getErrorMessageRistoratore(responseRistoratore), Toast.LENGTH_SHORT).show();
                }
        }
    }

ParseContentRistoratore.java

class ParseContentRistoratore {

    private final String KEY_SUCCESSRistoratore = "statusr";
    private final String KEY_MSGRistoratore = "message";
    private final String KEY_AddressListRistoratore = "addressList";
    private final String KEY_DATARistoratore = "Data";
    private  ArrayList<HashMap<String, String>> hashMapRistoratore;
    private Activity activityRistoratore;
    private PreferenceHelperRistoratore preferenceHelperRistoratore;

    ArrayList<HashMap<String, String>> arraylistRistoratore;

    ParseContentRistoratore(Activity activityRistoratore) {
        this.activityRistoratore = activityRistoratore;
        preferenceHelperRistoratore = new PreferenceHelperRistoratore(activityRistoratore);

    }

    boolean isSuccessRistoratore(String responseRistoratore) {
        try {
            JSONObject jsonObjectRistoratore = new JSONObject(responseRistoratore);
            if (jsonObjectRistoratore.optString(KEY_SUCCESSRistoratore).equals("truer")) {
                return true;
            } else {

                return false;
            }

        } catch (JSONException eRistoratore) {
            eRistoratore.printStackTrace();
        }
        return false;
    }

    String getErrorMessageRistoratore(String responseRistoratore) {
        try {
            JSONObject jsonObjectRistoratore = new JSONObject(responseRistoratore);
            return jsonObjectRistoratore.getString(KEY_MSGRistoratore);

        } catch (JSONException eRistoratore) {
            eRistoratore.printStackTrace();
        }
        return "No data";
    }

    void saveInfoRistoratore(String responseRistoratore) {
        preferenceHelperRistoratore.putIsLoginRistoratore(true);
        try {
            JSONObject jsonObjectRistoratore = new JSONObject(responseRistoratore);
            if (jsonObjectRistoratore.getString(KEY_SUCCESSRistoratore).equals("truer")) {
                JSONArray dataArrayRistoratore = jsonObjectRistoratore.getJSONArray("datar");
                for (int i = 0; i < dataArrayRistoratore.length(); i++) {

                    JSONObject dataobjRistoratore = dataArrayRistoratore.getJSONObject(i);
                    preferenceHelperRistoratore.putNomeRistoratore(dataobjRistoratore.getString(AndyConstantsRistoratore.ParamsRistoratore.NOMERistoratore));
                    preferenceHelperRistoratore.putCognomeRistoratore(dataobjRistoratore.getString(AndyConstantsRistoratore.ParamsRistoratore.COGNOMERistoratore));
                    preferenceHelperRistoratore.putNomeRistorante(dataobjRistoratore.getString(AndyConstantsRistoratore.ParamsRistoratore.RISTORANTEmono));
                }
            }
        } catch (JSONException eRistoratore) {
            eRistoratore.printStackTrace();
        }

    }
}

Login.java

 //LOGIN
    @SuppressLint("StaticFieldLeak")
    private void loginRistoratore() throws IOException, JSONException {

        if (!AndyUtilsRistoratore.isNetworkAvailableRistoratore(r_start.this)) {
            Toast.makeText(r_start.this, "Internet is required!", Toast.LENGTH_SHORT).show();
            return;
        }
        AndyUtilsRistoratore.showSimpleProgressDialogRistoratore(r_start.this);
        final HashMap<String, String> map = new HashMap<>();
        map.put(AndyConstantsRistoratore.ParamsRistoratore.IDRistoratore, editUserId.getText().toString());
        map.put(AndyConstantsRistoratore.ParamsRistoratore.CELLRistoratore, edtPhone.getText().toString());
        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                try {
                    HttpRequestRistoratore req = new HttpRequestRistoratore(AndyConstantsRistoratore.ServiceTypeRistoratore.LOGINRistoratore);
                    response = req.prepareRistoratore(HttpRequestRistoratore.Method.POST).withDataRistoratore(map).sendAndReadStringRistoratore();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss", result);
                onTaskCompletedRistoratore(result,LoginTaskRistoratore);
            }
        }.execute();
    }

    private void onTaskCompletedRistoratore(String response,int task) {
        Log.d("responsejson", response.toString());
        AndyUtilsRistoratore.removeSimpleProgressDialogRistoratore();  //will remove progress dialog
        switch (task) {
            case LoginTaskRistoratore:
                if (parseContent.isSuccessRistoratore(response)) {
                    parseContent.saveInfoRistoratore(response);
                    Toast.makeText(r_start.this, "Accesso eseguito", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(r_start.this,RistoratoreHome.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    this.finish();
                }else {
                    Toast.makeText(r_start.this, parseContent.getErrorMessageRistoratore(response), Toast.LENGTH_SHORT).show();
                }
        }
    }
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号