0

I want to make login and registration in my UWP app using PHP and MySQL

I use this code below to do it but it didn't work

I try many ways in internet but its so old

I make PHP and MySQL Database in a localhost xampp

I'm beginner in PHP so pleas anyone tell me the error in my code

I use this code to POST data to serve in UWP :

private async void Button_Click(object sender, RoutedEventArgs e)
{
  Uri requestUri = new Uri("http://localhost/test/index.php"); 

  HttpStringContent stringContent = new HttpStringContent
     (" { \"email\": \"" + emailbox.Text + "\" , \"password\":\"" + passwordbox.Text + "\" } " 
        , Windows.Storage.Streams.UnicodeEncoding.Utf8 
        , "application/json");

  //Dictionary<string, string> pairs = new Dictionary<string, string>();
  //pairs.Add("email", emailbox.Text);
  //pairs.Add("password", passwordbox.Text);
  //HttpFormUrlEncodedContent encodedContent = new HttpFormUrlEncodedContent(pairs);

  Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();

  await client.PostAsync(requestUri, stringContent);           
}

And This is my PHP backend code

config.php

<?php

define("DB_HOST","127.0.0.1");
define("DB_USER","root");
define("DB_PASSWORD","");
define("DB_NAME","firstdb");

?> 

db_connect.php

<?php

    include_once 'config.php';

    class DbConnect{

        private $connect;

        public function __construct(){

            $this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

            if (mysqli_connect_errno($this->connect)){
                echo "Unable to connect to MySQL Database: " . mysqli_connect_error();
            }
        }

        public function getDb(){
            return $this->connect;
        }
    }
?>

user.php

<?php

    include_once 'db_connect.php';

    class User{

        private $db;

        private $db_table = "users";

        public function __construct(){
            $this->db = new DbConnect();
        }

        public function isLoginExist($email, $password){

            $query = "select * from ".$this->db_table." where email = '$email' AND password = '$password' Limit 1";

            $result = mysqli_query($this->db->getDb(), $query);

            if(mysqli_num_rows($result) > 0){

                mysqli_close($this->db->getDb());


                return true;

            }

            mysqli_close($this->db->getDb());

            return false;

        }

        public function isEmailUsernameExist($email){

            $query = "select * from ".$this->db_table." where email = '$email'";

            $result = mysqli_query($this->db->getDb(), $query);

            if(mysqli_num_rows($result) > 0){

                mysqli_close($this->db->getDb());

                return true;

            }

            return false;

        }

        public function isValidEmail($email){
            return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
        }

        public function createNewRegisterUser( $email, $password){

            $isExisting = $this->isEmailUsernameExist($email);

            if($isExisting){

                $json['success'] = 0;
                $json['message'] = "Error in registering. Probably the username/email already exists";
            }

            else{

            $isValid = $this->isValidEmail($email);

                if($isValid)
                {
                $query = "insert into ".$this->db_table." (email, password) values ('$email','$password')";

                $inserted = mysqli_query($this->db->getDb(), $query);

                if($inserted == 1){

                    $json['success'] = 1;
                    $json['message'] = "Successfully registered the user";

                }else{

                    $json['success'] = 0;
                    $json['message'] = "Error in registering. Probably the username/email already exists";

                }

                mysqli_close($this->db->getDb());
                }
                else{
                    $json['success'] = 0;
                    $json['message'] = "Error in registering. Email Address is not valid";
                }

            }

            return $json;

        }

        public function loginUsers($email, $password){

            $json = array();

            $canUserLogin = $this->isLoginExist($email, $password);

            if($canUserLogin){

                $json['success'] = 1;
                $json['message'] = "Successfully logged in";

            }else{
                $json['success'] = 0;
                $json['message'] = "Incorrect details";
            }
            return $json;
        }
    }
?>

index.php

<?php

    require_once 'user.php';

    $username = "";

    $password = "";

    $email = "";
    if(isset($_POST['email'] && isset($_POST['password']))){

        $email = $_POST['email'];

    }

    if(isset($_POST['password'])){

        $password = $_POST['password'];

    }


    $userObject = new User();

    // Registration

    if(!empty($password) && !empty($email)){

        $hashed_password = md5($password);

        $json_registration = $userObject->createNewRegisterUser($email, $hashed_password);

        echo json_encode($json_registration);

    }

    // Login

    if(!empty($password) && empty($email)){

        $hashed_password = md5($password);

        $json_array = $userObject->loginUsers($email, $hashed_password);

        echo json_encode($json_array);
    }
?>
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Sep 01 '17 at 14:37
  • 1
    ***You really shouldn't use [MD5 password hashes](http://security.stackexchange.com/questions/19906/is-md5-considered-insecure)*** Please use ***PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html)*** to handle password security. ***It is not necessary to [escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Sep 01 '17 at 14:37
  • Thank you for this information but is it the problem my code didn't work ?? – John Michael Sep 01 '17 at 14:41
  • 1
    Have you checked the error logs for your web server? You're using MD5 to register, but your not using it to login, so the passwords will never match. – Jay Blanchard Sep 01 '17 at 14:42
  • `(" { \"email\": \"" + emailbox.Text + "\" , \"password\":\"" + passwordbox.Text + "\" } "` Yuk. Use a JSON serialiser. – ADyson Sep 01 '17 at 15:32
  • "is it the problem my code didn't work ?? " Unlikely to be, at least not directly, but it's certainly a massive security vulnerability, especially in code which is to do with logins/security. You should definitely change all the suggested things before putting it live. – ADyson Sep 01 '17 at 15:33

1 Answers1

0

I would recommend you to use a Password Entry instead of a visible entry in your app like a PasswordBox. Try to make your request like that.

var loginUrl = "http://localhost/test/index.php";

using (var client = new HttpClient())
{
                var values = new Dictionary<string, string>
            { { "username", emailbox.Text }, { "password", passwordbox.Text } };

                var content = new FormUrlEncodedContent(values);
                var response = await client.PostAsync(loginUrl, content);
                string result = await response.Content.ReadAsStringAsync(); 
}
GeralexGR
  • 2,973
  • 6
  • 24
  • 33