Android Code Snippet Security PHP+MD5+TOKEN Config

Hi all!
i made a changes in the code posted many times on the forum

https://www.b4x.com/android/forum/t...er-using-httputils2-part-1-php.42442/#content

https://www.b4x.com/android/forum/threads/connect-android-to-mysql-database-tutorial.8339/#content

and more....
here is the OLD code using mysql_connect
PHP:
<?

$databasehost = "localhost";
$databasename = "xxxx";
$databaseusername ="xxxx";
$databasepassword = "xxxx";

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
$query = file_get_contents("php://input");
$sth = mysql_query($query);

if (mysql_errno()) {
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error();
}
else
{
    $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>

now i go share the new code using PDO + token.
Its make the config safer, and the querys are stored on the php file and not on the app.

PHP:
<?php

$databasehost = "localhost";
$databasename = "";
$databaseusername ="";
$databasepassword = "";

try{

$connection = new PDO("mysql:dbname=$databasename;host=$databasehost;port=3306", $databaseusername, $databasepassword);

} catch (Exception $e) {

    echo exit($e->getMessage());
}


$connection->query("SET CHARACTER SET utf8");


if($_GET['token'] != md5('casa')) {
    die('HUE');
}

switch($_GET["do"])
{

     case "teste":

         $res = $connection->prepare('SELECT * FROM signups');
      
         $res->execute();
         $void = false;

         break;


     case "add-admin":

         #you can change $_GET for $_POST TOO

         #URL SAMPLE -> HTTP://LOCALHOST/ESTEARQUIVO.PHP?do=add-admin&[email protected]&passwd=123
         $res = $connection->prepare('INSERT INTO tbladmin (email,passwd) values (?,?)');

         $res->execute(array($_GET['mail'], md5($_GET['passwd']));
         $void = true;

         break;
}

if (isset($res->errorInfo()[2])) {
     header("HTTP/1.1 500 Internal Server Error");
     echo $res->queryString.'\n';
     echo $res->errorInfo()[2];
}

else
{

    if(!$void) {
        $rows = array();
            foreach($res->fetchAll(PDO::FETCH_ASSOC) as $value) {

                $rows[] = $value;
            }

    } else {
        $rows = true;
    }

    print json_encode($rows);
}
?>



To send POST or GET for this php file you need...
- A app token in (MD5)

to make a md5 on the b4a you can use this code
B4X:
Private pi As String
    pi = "casa"
    Dim md As MessageDigest
    Dim ByteCon As ByteConverter
    Dim passwordhash() As Byte
    Dim passwordhash2() As Byte
    passwordhash = md.GetMessageDigest(pi.GetBytes("UTF8"),"MD5")
    Dim md5string As String
    md5string = ByteCon.HexFromBytes(passwordhash)
    md5string = md5string.ToLowerCase
    Log(md5string)
MD5 hash for casa is : 202447d5d44ce12531f7207cb33b6bf7

on the php file you go compare on this if
PHP:
if($_GET['token'] != md5('casa')) {
    die('HUE');
}

the url in this case is

www.mysite.com/include/config.php?token=202447d5d44ce12531f7207cb33b6bf7

no
w how to send post and get?


B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim job1, job2, job3 As HttpJob
   job1.Initialize("Job1", Me)

   'Send a GET request
   job1.Download2("http://www.mysite.com/include/config.php?token=202447d5d44ce12531f7207cb33b6bf7", _
      Array As String("do", "teste"))

   'Send a POST request
   job2.Initialize("Job2", Me)
   job2.PostString(""http://www.mysite.com/include/config.php?token=202447d5d44ce12531f7207cb33b6bf7"", "do=add-admin&[email protected]&passwd=dwdwd15115151")


End Sub

Sub JobDone (Job As HttpJob)
   Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
   If Job.Success = True Then
      Select Job.JobName
         Case "Job1", "Job2"
            'print the result to the logs
            Log(Job.GetString)

      End Select
   Else
      Log("Error: " & Job.ErrorMessage)
      ToastMessageShow("Error: " & Job.ErrorMessage, True)
   End If
   Job.Release
End Sub

note in the php example the add-admin is $_GET for send post you need change $_GET to $_POST
the result is a JSON result normal.

its recomended you use.
-HTTPS if you have
-Release Obfuscated
-send and store all pass on md5
-Use this file on a Folder named include, and the file with name config.php

mysite.com/include/config.php

if you is a php coder, can give sugestions and post your code here to help all.
 
Last edited:
Top