Я создаю приложение для Android, в котором пользователи могут register
и login
.
На данный момент регистрация и вход в систему работают отлично.
Но код PHP
уязвим для атак SQL Injection
, поэтому я хочу сделать его безопасным, используя PDO
.
Когда пользователь регистрируется, его Name
и Surname
сохраняются в Shared Preferences
, и он показывает это в своем Home activity
.
Проблема в том, что когда я использую скрипт Login
с PDO
, переменные в SharedPreferences
неверны.
Если у меня есть 10 users
, он показывает мне имя и фамилию user 1
, даже если я вхожу в систему с user 2
, user 3
, user 4
и т.д ...
Более того, если я использую файл Register.php
с PDO
, это не спасет меня от имени и фамилии всех пользователей в SharedPreferences
.
Итак, я хочу понять, почему SharedPrefrences
не работает после изменения моего PHP
файла?
Что я не так с файлом PHP
с PDO
?
У кого-нибудь есть советы для меня?
Я охотно слушаю вас.
Login.php Без 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 с 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 без 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 с 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();
}
}
}