Sending a string from an app to a server - php

I have been working on an app which will send a string to a database on my server, however for some reason no data is received. Maybe you could point me in the right direction, I have been searching all over the net but can't find the reason why it's not working.
My android code:
public class HttpURLConnectionHandler
{
protected String urlG = "http://example.com/";
public String sendText(String text)
{
try {
URL url = new URL(urlG+"phpcode.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes("mydata:"+text);
wr.flush();
wr.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
catch(Exception e){ return "error";}
}
}
My code in php:
<?php
$servername = "here is my server";
$username = "my username";
$password = "my pass";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$image = $_POST['image'];
$sql = "INSERT INTO photos (image)
VALUES ('{$image}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The way I call my class is:
HttpURLConnectionHandler handler= new HttpURLConnectionHandler();
String response = handler.sendText("this is a text");

I let you look around Retrofit

You trying to get value of POST variable image in your PHP, but you sending variable mydata.

Related

Unable to fetch data from $_POST variable in PHP to Android Studio

I want to fetch the content of $_POST variable from a PHP hosted file into Android app. I have tried using Jsoup and Volley libraries to do this but they were not producing the expected result. Later, found out that echo ("anyString"); is being fetched to android but echo($_POST["orderId"]); is not being fetched even though it gets printed in web page. Is there any way of solving this issue?
This is the PHP code:
<?php
$secretkey = "7457645673urgjnjkf784jyj66545y";
$orderId = $_POST["orderId"];
$orderAmount = $_POST["orderAmount"];
$referenceId = $_POST["referenceId"];
$txStatus = $_POST["txStatus"];
$paymentMode = $_POST["paymentMode"];
$txMsg = $_POST["txMsg"];
$txTime = $_POST["txTime"];
$signature = $_POST["signature"];
$data = $orderId.$orderAmount.$referenceId.$txStatus.$paymentMode.$txMsg.$txTime;
$hash_hmac = hash_hmac('sha256', $data, $secretkey, true) ;
$computedSignature = base64_encode($hash_hmac);
if ($signature == $computedSignature) {
echo json_encode($_POST);
}
?>
The java code in Android:
URL link = new URL("https://sample.php");
HttpURLConnection conn;
conn = (HttpURLConnection) link.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("result", result.toString());
}
}catch (Exception e){
Log.d("result", e.toString());
}

Use of $_POST when php file is called by android app

I'm trying to upload some data in the database with an android app. Until now everything was working fine, but now I need to add another column, so I modified the code and now it looks like the data sent by the phone is not readable by my php files. The important part of the code of my app is the following:
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
//conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
Log.v(TAG, "Has posted" + bytes);
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
Log.v(TAG, "Post Failed");
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
On the Logcat it looks like the app has been able to post the code effectively in byte format:
V/Alvaro Lloret GCM﹕ Posting email=llor&name=hola&arduinoweb=jaj&regId=APA' to http://youdomotics.com/mysecurity1/register.php
E/URL﹕ > http://website.com/mysecurity1/register.php
V/RenderScript﹕ Application requested CPU execution
V/RenderScript﹕ 0xaec16400 Launching thread(s), CPUs 4
V/Alvaro Lloret GCM﹕ Has posted[B#16d173b0
V/GCMRegistrar﹕ Setting registeredOnServer status as true until 2015-09-11 20:21:30.364
V/GCMBaseIntentService﹕ Releasing wakelock
Then, the code to receive the post with php is the following:
<?php
// response json
$json = array();
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["regId"]) ) {
require("config.php");
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$name = $_POST["name"];
$email = $_POST["email"];
$arduinoweb = $_POST["arduinoweb"];
$gcm_regid = $_POST["regId"]; // GCM Registration ID
include_once './gcm.php';
$query = "INSERT INTO gcm_users_new(name, email, gcm_regid, arduinoweb, created_at) VALUES('$name', '$email', '$gcm_regid', '$arduinoweb', NOW())";
mysqli_query($con, $query);
} else {
// user details missing
}
?>
This code worked perfectly without the new parameter arduinoweb, but since I added this other parameter, the row is not added into the database. If I comment the condition if (isset...), then the file adds a row in the table, but it's empty...
Any ideas?
Thank you!!
Okay I solved!
The perfect answer is here
I just had to change to www. when I called the URL and that made it work!

PHP inserts blank row into mysql table from android app

I am inserting json data from my android app in my device into xampp server in my computer using POST. It simply inserts row with empty column. When I enter the column from my browser using GET it converts it to numbers only eventhough the data is mix of numbers and letters. The type of the table column is varbinary. I entered 'crap' from my browser and it was inserted as '63726170' in the table. I am puzzled by this. Here is the PHP code that inserts the data.
if (isset($_POST)){
//sanitize the input
filter_var_array($_POST);
$ri=$_POST['regID'];
$id=json_decode($ri);
//$decoid= $id->regID;
if(is_array($id)){
foreach ($id as $key=>$value){
$fu=$id[$key];
};
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO regids (regID)
VALUES ('$fu')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}else{
echo "Error executing query!!!";
}
$conn = null;
I am adding my android code that is sending the data to the server
URL url;
HttpURLConnection urlConn;
DataOutputStream printout;
url = new URL ("myurlhere");
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
/*List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("regID", result));*/
String result = args.toString();
try{
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("regID", result);
String postData="json="+jsonParam.toString();
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
Log.i("NOTIFICATION", "Data Sent");
printout.flush ();
printout.close ();
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line; }
Log.i("msg=",""+msg);
os.close();

Connecting Android to MySQL

So I'm really new to this. I was following a tutorial on web that showed how to connect these two. But everything I do it just jumps to catch part and it says "No connection". What am I missing? I also connect to a http server to use a PHP script which queries username and password from the database.
try
{
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200)
{
entity = response.getEntity();
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonResponse = new JSONObject(instream.toString());
String retUser = jsonResponse.getString("upime");
String retPass = jsonResponse.getString("geslo");
if(username.equals(retUser) && password.equals(retPass))
{
SharedPreferences sp = getSharedPreferences("logindetails", 0);
SharedPreferences.Editor spedit = sp.edit();
spedit.putString("upime", username);
spedit.putString("geslo", password);
spedit.commit();
Toast.makeText(getBaseContext(), "Login successful", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Failed to login", Toast.LENGTH_SHORT).show();
}
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "No connection", Toast.LENGTH_LONG).show();
}
<?php
header('Content-Type: application/json');
$dbhost ="localhost";
$dbuser = "username";
$dbpass = "password";
$dbdb = "db";
$connect = mysql_connect($db_host, $dbuser, $dbpass) or die("connection error");
mysql_select_db($dbdb);
$username =$_POST['username'];
$password=$_POST['password'];
$query = mysql_query("SELECT * FROM users WHERE user='$username' AND pass='$password'");
$num = mysql_num_rows($query);
if($num == 1)
{
while($list=mysql_fetch_assoc($query))
{ $output = $list;
}
mysql_close();
echo json_encode($output);
?>
edit the final "echou" to echo and add
header('Content-Type: application/json');
You have to create webservice in which php code is written. web service can be soap and Rest. and you have to write url of webservice in http client object.
By doing this you can connect android and mysql.
HttpPost postD=new HttpPost("url");
Have you given Internet Permission in your android manifest?
<uses-permission android:name="android.permission.INTERNET" />

Connecting mysql database with Android app

I have a problem connecting database with Android app. I am trying to implement this tutorial. Everything seems to be fine but I neither get any success not an error.
There is a button listener which on clicking does a post to a PHP file and gets the result. Here is the code for it:-
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/check.php", postParameters);
String res=response.toString();
Log.d("res:", res);
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
Here is the http post method:-
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.d("postMethodReturn", result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The PHP code is as below:-
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = "xyz";
$pswd = "xyz";
$db = "mydb";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//run the query to search for the username and password the match
$query = "SELECT * FROM mytable WHERE user = '$un' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) --> 0)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Is there any bug in the program? I tried logging the intermediate values of res (http response) in activity code and result in the execute post method, but nothing is being logged. Tried changing "localhost" to "127.0.0.1" and also into a publicly available webhost, with all the database environment, but no success. All these on emulator and with public host, tried with real device too. Server seems to be running when checked from browser. Database exists with the values. All services running (apache, mysql).
The main problem is that there is no error! Any suggestions what is going wrong?
Couldn't find anyone with the same problem.
the problem was --> in the PHP code. changed it to == or > and everything works fine!

Categories