PDO search query help! [unity3D] - php

PHP
dispdb.php
<?php
// Configuration
$hostname = '1(Ignore this)';
$username = '1(Ignore this)';
$password = '1(Ignore this)';
$database = '1(Ignore this)';
$secretKey = "1(Ignore this)";
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$realHash = md5($_GET['search'] . $secretKey);
if($realHash == $hash){
$sth = $dbh->query('SELECT * FROM `oidevstool` WHERE `id` =:search ORDER BY `id`');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();
if(count($result) > 0) {
foreach($result as $r) {
echo $r['id'] . "/" . $r['title'] . "/" . $r['priority'] . "/" . $r['deadline'] . "/" . $r['comment'];
}
}
}
?>
database.cs
using UnityEngine;
using System.Collections;
public class database : MonoBehaviour {
private string secretKey = "1(Don't mid this)"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "1(Don't mid this)"; //be sure to add a ? to your url
public string highscoreURL = "http://example.com/dispdb.php?";
public string dataRetrieved;
public string search;
public string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores()
{
string hash = Md5Sum(search + secretKey);
string post_url = highscoreURL + "search=" + search + "&hash=" + hash;
WWW hs_post = new WWW(post_url);
WWW hs_get = new WWW(highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
dataRetrieved = hs_get.text;
}
}
void OnGUI()
{
GUI.Box(new Rect(0, 0, 800, 800), dataRetrieved);
search = GUI.TextField(new Rect(805, 0, 200, 30), search);
if(GUI.Button(new Rect(805, 35, 200, 30), "Search"))
{
StartCoroutine(GetScores());
}
}
}
i've looking ways to fix but i couldn't find any help for some reason this doesn't work whenever i pressed searched on Unity3D it didn't even show the "success", eventhough i made when hash are correct get data
any chance of someone going to help me?
that't will be very appreciated
Thankyou.
Best Regards

You are using a named placeholder :search in query() .
Use prepare() then either bind :search and execute() or use "lazy" binding by passing data into execute().
See PDO info for more

if($realHash = $hash){ should be if($realHash === $hash){

Related

android uploading empty image to the host using php

I'm trying to upload a photo from an android device to host using PHP and base 64, bitmap ; but it uploads two empty images (it uploads two times) can't figure out why, any help or alternative way?
I'm uploading the photo in a register layout so I tried just inserting the photo without anything else, and I tried using another hosting service but unfortunately, nothing worked.
the name of the empty photo is inserted in the database yet in the file manager it's an empty photo
the php code;
<?php
// array for JSON response
$response = array();
$user_image= $_POST['user_image'];
$user_name= $_POST['user_name'];
$user_email= $_POST['user_email'];
$user_un= $_POST['user_un'];
$user_pass= $_POST['user_pass'];
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$ra=rand(0,20000);
$rn=rand(0,40000);
$rd=rand(0,60000);
$imgname = "pl".$ra.$rn.$rd.".jpeg";
$decoding=base64_decode("$user_image");
file_put_contents("images/".$imgname,$decoding);
$sql = "INSERT INTO Users (user_name,user_email,user_un,user_pass,user_image)
VALUES ('$user_name','$user_email','$user_un','$user_pass','$imgname')";
if ($conn->query($sql) === TRUE) {
$UserId = $conn->insert_id;
$response['dishs'] = array();
$hobbie['status'] = "ok";
$hobbie['result'] = "Welcome";
// push single dishinto final response array
array_push($response['dishs'],$hobbie);
// echoing JSON response
echo json_encode($response);
} else {
// echo "Error: " . $sql . "" . $conn->error;
$response['dishs'] = array();
// failed to insert row
$hobbie['status'] = "no";
$hobbie['result'] = "Error: " . $sql . "" . $conn->error;
array_push($response['dishs'],$hobbie);
// echo no users JSON
echo json_encode($response);
}
}
$conn->close();
?>
the kotlin code
these are defined in the head of the class
"class RegisterPage :Fragment() {
var encodImg = ""
var bitmap: Bitmap? = null
......
"
sending this to the host
"... val params = HashMap<String, String>()
params["user_image"] = encodImg
...
"
the way i choose the photo from gallery and encrypt
private fun startGallery() {
val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.type = "image/*"
if (galleryIntent.resolveActivity(activity!!.packageManager) != null) {
startActivityForResult(galleryIntent, 1000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, i: Intent?) {
super.onActivityResult(requestCode, resultCode, i)
if (resultCode == Activity.RESULT_OK) {
val uri: Uri? = i!!.data
change_profile_photo.setImageURI(uri)
manageImageFromUri(i.data!!)
} else {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show()
}
}
private fun manageImageFromUri(imageUri: Uri) {
val baos = ByteArrayOutputStream()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Snackbar.make(view!!, "ERROR", Snackbar.LENGTH_LONG)
} else {
bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imageUri)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
encodImg = Base64.encodeToString(b, Base64.DEFAULT)
}
}
}

Unity and MySQL can't register many Chinese

I am making register and log in .
When I input over two Chinese words , it's can't register.
Only one Chinese word can register.
I add the Chinese words to username from phpMyadmin and it can log in!
Why I can't register many Chinese at start?
please help me !
PHP:
<?php
$con = mysqli_connect('xxxx:3306', 'root', 'xxxx', 'xxxx');
if(mysqli_connect_errno())
{
echo "1: Connection failed";
exit();
}
$username = $_POST["name"];
$password = $_POST["password"];
$gender = $_POST["gender"];
$namecheckquery = "SELECT username FROM players WHERE username='" . $username . "';";
$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed");
if (mysqli_num_rows($namecheck) > 0)
{
echo "3:Name already exists";
exit();
}
$salt = "\$5\$rounds=5000\$" . "steamedhams" . $username . "\$";
$hash = crypt($password, $salt);
$insertuserquery = "INSERT INTO players (username, hash,salt,gender) VALUES
('" . $username."', '" . $hash . "', '". $salt."','".$gender."');";
mysqli_query($con, $insertuserquery) or die ("4: Insert player query failed");
echo ("0"); ?>
My code in Unity
public class Registration : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Button submitButton;
public Button boyButton;
public Button girlButton;
public void CallRegister()
{
StartCoroutine(Register());
}
IEnumerator Register()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
form.AddField("password", passwordField.text);
WWW www = new WWW("http://localhost/sqlconnect/register.php", form);
yield return www;
if(www.text =="0")
{
Debug.Log("User created successfully");
UnityEngine.SceneManagement.SceneManager.LoadScene("mainmenu");
}
else
{
Debug.Log("User creation failed. Error #" + www.text);
}
}
public void VerifyInputs()
{
submitButton.interactable = (nameField.text.Length >= 1 && passwordField.text.Length >= 4);
}
}
I'm not sure but my guess would be that WWW does not automatically escape spaces in the provided form or have encoding errors.
In general you should try and rather use UnityWebRequest.Post which clearly states:
The data in postData will be escaped, then interpreted into a byte stream via System.Text.Encoding.UTF8.
which might solve your problem
private IEnumerator Register()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
form.AddField("password", passwordField.text);
using(var www = UnityWebRequest.Post("http://localhost/sqlconnect/register.php", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
return;
}
if(string.Equals(www.downloadHandler.text, "0"))
{
Debug.Log("User created successfully");
UnityEngine.SceneManagement.SceneManager.LoadScene("mainmenu");
}
else
{
Debug.Log("User creation failed. Error #" + www.text);
}
}
}

WWW in Unity returning empty string

Its returning an empty string and I can't seem to figure out why, if you visit the page it outputs fine. (http://lgdev.site.nfoservers.com/getItems.php). I'm trying to get all the data, separate it by certain characters, then use the code in the game t operate it and sort it into the correct places. But like I said its returning an empty string instead of the data that's show on the webpage I gave above.
Game Code:
public void loadItems()
{
WWWForm form = new WWWForm();
WWW w = new WWW("http://lgdev.site.nfoservers.com/getItems.php", form);
StartCoroutine(loadItemsFunc(w));
}
IEnumerator loadItemsFunc(WWW w)
{
yield return w;
Debug.Log(w.text);
string[] tmpdata1 = w.text.Split(char.Parse("="));
foreach(string data in tmpdata1)
{
string[] tmpinfo = data.Split(char.Parse("~"));
GameObject tmpObj = Instantiate(weapon);
tmpObj.GetComponent<weapon>().name = tmpinfo[0];
tmpObj.GetComponent<weapon>().vitalisim = int.Parse(tmpinfo[1]);
tmpObj.GetComponent<weapon>().defence = int.Parse(tmpinfo[2]);
tmpObj.GetComponent<weapon>().strength = int.Parse(tmpinfo[3]);
string[] offsetInfo1 = tmpinfo[5].Split(char.Parse(";"));
foreach (string off in offsetInfo1)
{
string[] offset = off.Split(char.Parse(","));
tmpObj.GetComponent<weapon>().offsetsPos.Add(new Vector3(float.Parse(offset[0]), float.Parse(offset[1]), float.Parse(offset[2])));
tmpObj.GetComponent<weapon>().offetsRot.Add(new Vector3(float.Parse(offset[3]), float.Parse(offset[4]), float.Parse(offset[5])));
tmpObj.GetComponent<weapon>().offetsSize.Add(new Vector3(float.Parse(offset[6]), float.Parse(offset[7]), float.Parse(offset[8])));
}
string[] typeInfo = tmpinfo[4].Split(char.Parse(","));
if (tmpinfo[1] == "SwordnShield")
{
tmpObj.GetComponent<weapon>().anim = swordAndShieldAnimSet;
}
else if (tmpinfo[1] == "TwoHanded")
{
tmpObj.GetComponent<weapon>().anim = twoHandedAnimSet;
}
foreach (string prefab in tmpinfo[6].Split(char.Parse(",")))
{
tmpObj.GetComponent<weapon>().prefabs.Add(prefab);
}
}
}
PHP Code:
<?PHP
$con = mysql_connect("localhost","user","passs") or ("Cannot connect!" . mysql_error());
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("lgdev_projectzed" , $con) or die ("could not load the database" . mysql_error());
$query = "SELECT * FROM `equipment`";
$check = mysql_query($query) or die(mysql_error()." ".$query);
if($check){
}
$numrows = mysql_num_rows($check);
$text = "";
while ($row = mysql_fetch_array($check, MYSQL_ASSOC)) {
$text = $text."".$row["name"]."~".$row["vitalism"]."~".$row["defence"]."~".$row["strength"]."~".$row["type"]."~".$row["offsets"]."~". $row["prefabs"] ."=";
}
die($text);
?>
First, check if it gives any error with:
Debug.Log(w.error); // place this before or after the other debug.log
Since the form that you submit is empty, there is some error..
So check how to setup your form:
https://docs.unity3d.com/ScriptReference/WWWForm.html
If you don't need to post anything in the form, can use the plain WWW
https://docs.unity3d.com/ScriptReference/WWW.html

PHP password_verify incorrectly returning false

I've searched high and low for this topic, and no one has the same issue I'm experiencing that I could find.
I'm creating a user in a MySQL table, with a hash from password_hash with a strength of 10.
I've been having hell getting it to validate, and have a test script made to actually validate my findings. Here is the script:
public function testAction(){
$data = new dataHandler;
$data->table = "access";
$hash1 = $data->insert(array('email'=>'test6#test.com', 'password'=>'ABC123.abc', 'password_confirm'=>'ABC123.abc', 'alias'=>'ABC123.abc'));
$res = $data->find(array('email'=>'test6#test.com'));
$hash2 = $res[0]['hash'];
$test = password_verify('ABC123.abc', $hash1);
$test2 = password_verify('ABC123.abc', $hash2);
var_dump($test);
echo "<br>";
var_dump($test2);
echo "<br><br>";
echo "Length: " . strlen($hash1) . "<br>{$hash1}<br>Length: " . strlen($hash2) . "<br>{$hash2}";
die();
}
To verify that my script wasn't somehow doing something weird when storing, I made my hash method (called from within the insert() method dynamically) echo out the hash directly:
public function createHash($password){
$hash = password_hash($password, HASH);
echo "Length: " . strlen($hash) . "<br>$hash<br>";
return $hash;
}
Here's the insert method. cleanData simply unsets anything not available in a describe - it is not changing any values whatsoever. Warning, it's terribly ugly presently due to a lot of debugging and such:
public function insert($data){
if(!is_array($data)){
return false;
} else {
$this->openDb();
$ins = "";
$fs = "";
$data = $this->cleanData($data);
foreach($data as $key => $field){
if($key == "password"){
$auth = new authorization;
$key = "hash";
$field = $auth->createHash($field);
$data['hash'] = $field;
unset($data["password"]);
}
$ins .= ":{$key}, ";
$fs .= "`{$key}`, ";
//$data[$key] = $this->DBH->quote($field);
}
$ins = rtrim($ins, ", ");
$fs = rtrim($fs, ", ");
try {
# the shortcut!
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$STH = $this->DBH->prepare("INSERT INTO `" . $this->table . "` ($fs) value ($ins)");
$STH->execute($data);
$id = $this->DBH->lastInsertId();
$this->closeDb();
return $data['hash']; //Debugging
return $id;
} catch(PDOException $e) {
$this->errHandler($e->getMessage());
}
}
}
Now, here's the output:
Length: 60
$2y$10$wGJxGjK4Lz4FgZ3OZJjBo.9lF7LE90p3Q5inOsBROQTU5FBVdj1LK
bool(true)
bool(false)
Length: 60
$2y$10$wGJxGjK4Lz4FgZ3OZJjBo.9lF7LE90p3Q5inOsBROQTU5FBVdj1LK
Length: 60
$2y$10$wGJxGjK4Lz4FgZ3OZJjBo.9lF7LE90p3Q5inOsBROQTU5FBVdj1LK
As you can see, both password_verify attempts fail. The first comes from the hash generation without any further manipulation, the second comes from the database.
What am I doing wrong?
The only thing I could find when searching was people testing and using double quotes, or random human error. This, however, doesn't appear to me to be either of those two.
That password hash is for the empty string, try it yourself:
<?php
echo password_verify('', '$2y$10$4Y7kQNP/6XyBtQQ4zPI6ZuaelCjHdWE.kBRTUVk56J7PV4BQYWoUS')?'Y':'N';
?>
Make sure you're passing createHash a valid $password.

Flex PHP service

Already tearing my hairs out for a couple of days. There is not much left of them ;-)
I am experiencing a strange problem when I want to bind a service to a button or something else:
files:
- CDPC.php
<?php
require_once ('VOcdpc.php');
class CDPC {
var $username = "root";
var $password = "";
var $server = "localhost";
var $port = "3306";
var $databasename = "xoffercommon";
var $tablename = "tblcity";
var $connection;
public function __construct() {
$this->connection = mysqli_connect(
$this->server,
$this->username,
$this->password,
$this->databasename,
$this->port
);
mysqli_set_charset($this->connection,'utf8');
$this->throwExceptionOnError($this->connection);
}
public function getCDPC($cityID) {
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xoffercommon", $con);
$cdpc_Id = new Vocdpc();
$cdpc_Id->id_cdpc = 1;
$cdpc_Id->city_Id=$cityID;
$result_prov = mysql_query("SELECT tblProvence_Id FROM tblCity WHERE Id = " . $cityID);
$row = mysql_fetch_array($result_prov);
$cdpc_Id->provence_Id=intval($row['tblProvence_Id']);
$result_dist = mysql_query("SELECT tblDistrict_Id FROM tblProvence WHERE Id = " . $cdpc_Id->provence_Id);
$row = mysql_fetch_array($result_dist);
$cdpc_Id->district_Id=intval($row['tblDistrict_Id']);
$result_coun = mysql_query("SELECT tblCountry_Id FROM tblDistrict WHERE Id = " . $cdpc_Id->district_Id);
$row = mysql_fetch_array($result_coun);
$cdpc_Id->country_Id=intval($row['tblCountry_Id']);
return $cdpc_Id;
mysql_close($con);
}
private function throwExceptionOnError($link = null) {
if($link == null) {
$link = $this->connection;
}
if(mysqli_error($link)) {
$msg = mysqli_errno($link) . ": " . mysqli_error($link);
throw new Exception('MySQL Error - '. $msg);
}
}
}
?>
VOcpdc.php
<?php
class VOcdpc
{
public $id_cdpc;
public $country_Id;
public $district_Id;
public $provence_Id;
public $city_Id;
// explicit actionscript class
var $_explicitType = "Vocdpc";
}
?>
In flex builder
I can add the services to the Data Services panel but I have two strange things:
1) when I want to configure the return type he doesn't let me create a new ValueObject type, I only get the bottom datagrid which states: Properties returned by the operation: Property: country_Id, provence_Id, city_Id, id_cdpc, district_Id with the related values on the right side. Why can't I create a new data type on the top?
2) When I accept this and want to add the service call to a button (drag&drop) I get the following error: Error occurred while generating code. Make sure that there are no compiler eroors and try again after reopening the file. Componentn type services.cdpc.CDPC not found...
(ps: When I perform a Test Operation everything seems to be ok, I get the expected output values)
this is the class included in the main cdpc.php file, the post drops it apparently, so here is the VOcpdc file:
// explicit actionscript class
var $_explicitType = "Vocdpc";
}
?>

Categories