Cannot acces post data sent from okhttp from php - php

i send post request with a json object to php in server, but php keep telling $_POST is empty.
this is okhttp code
public String postConection(JSONObject pJson, String pUrl) throws IOException {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String dirArchivo = "http://10.0.2.2/SoulStoreProject/"+pUrl;
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, pJson.toString());
Request request = new Request.Builder()
.url(dirArchivo)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
and this is the php code
$nick = $_POST['nick'];
$password = $_POST['password'];
$query = "
INSERT INTO
players(nick, password)
VALUES($nick,$password)
";
$DB->Execute($query);

You are posting in JSON format so you need to grab the post with file_get_contents('php://input') and then decode it so that you have it as an array.
$_POST only works with posts that are encoded with enctype=”multipart/form-data”
$post = json_decode(file_get_contents('php://input'),true);
$nick = $post['nick'];
$password = $post['password'];
$query = "INSERT INTO players(nick, password) VALUES(?,?)";
$sth = $DB->prepare($query);
$sth->Execute(array($nick, $password));

Related

How to get the JSON Object in PHP from Android OKHttp

I have my OkHttp code here (i'm working in Android)
void postRequest(String postUrl, String postBody) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON,postBody);
Request request = new Request.Builder()
.url(postUrl)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("TAG",response.body().string());
}
});
}
And this is my PHP part
<?php
header("Content-type: application/json; charset=utf-8");
include("conexion.php");
$nombre = $_POST["nombre"];
$apellidoPaterno = $_POST['apellidoPaterno'];
$apellidoMaterno = $_POST['apellidoMaterno'];
$direccion = $_POST['direccion'];
$redesSociales = $_POST['redesSociales'];
$telefono = $_POST['telefono'];
$nombreUsuario = $_POST['nombreUsuario'];
$contrasena = $_POST['contrasenaUsuario'];
?>
I want to obtain the values that are passing through my JSON, but when I use $_POST they end with no values. I've tried with the API of reqres and it does send the information.
Any help is appreciated, thanks.
Following your and my comments you could do the following:
<?php
// header("Content-type: application/json; charset=utf-8"); // not really needed here for now
include("conexion.php");
$fgc = file_get_contents("php://input");
$json = json_decode($fgc, true);
// now you've got all your values in $json:
$nombre = $json["nombre"];
alternatively you could do:
$json = json_decode($fgc);
// now you've got all your values as an object in $json:
$nombre = $json->nombre;
further reading: http://php.net/manual/de/wrappers.php.php#wrappers.php.input
try this:
//this only you use to issue a response in json format from your php to android
//header("Content-type: application/json; charset=utf-8");
include("conexion.php");
//The following lines serve to receive a json and transform them to the variables
$data = json_decode($_POST);
$nombre = $data->nombre;
$apellidoPaterno = $data->apellidoPaterno;
$apellidoMaterno = $data->apellidoMaterno;
$direccion = $data->direccion;
$redesSociales = $data->redesSociales;
$telefono = $data->telefono;
$nombreUsuario = $data->nombreUsuario;
$contrasena = $data->contrasenaUsuario;
Of course everything depends on how you are arming the body of the post sent, on the other hand if you are making a post request from android to your php, you do not need to convert the variables to json, just pass the body and already.
You must convert to JSON only the answers of your php towards android.
SAMPLE: https://ideone.com/x2ENdd

Unknown JSON error on my PHP server

I'm working on an application that allows data transfer from Android to PHP server and I don't know why it doesn't support JSON?
Here is my code:
<?php
JSON.parse();
$decode = json_decode($_REQUEST['request']);
$json = $decode->name;
header('Content-type:application/json');
echo json_encode($json);
?>
check your JSON at http://jsonlint.com
If the JSON is valid than your php code may not be correct.
Show some code for specifics.
You can send Json data as string from android using following code :
BufferedReader reader = null;
// Send data
try {
/* forming th java.net.URL object */
URL url = new URL(this.url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
/* pass post data */
byte[] outputBytes = jsonData.toString().getBytes("UTF-8");
OutputStream os = urlConnection.getOutputStream();
os.write(outputBytes);
os.close();
/* Get Response and execute WebService request*/
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == HttpsURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
ResponseData= convertStreamToString(inputStream);
} else {
ResponseData = null;
}
and in php,you can get data by adding following code :
$post_body = file_get_contents('php://input');
$post_body = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($post_body));
$reqData[] = json_decode($post_body);
$postData = $reqData[0];
echo $postData->name;

php connection with android project

I am a beginner in android development. I want to connect a php file to the android app. My php code is
<?php
$con = mysqli_connect("localhost", "root", "", "invoice_db");
if(mysqli_connect_errno($con)) {
echo "Failed to connect";
}
$response["sucess"]=0;
$invoiceid = $_POST['invc'];
$response = array();
$sql = "SELECT sl_no from invoice_table where invoice_id='$invoiceid'";
$result = mysqli_query($con,$sql);
if(!empty($result)) {
$row = mysqli_fetch_array($result);
$data = $row[0];
$response["sucess"] = 1;
}
mysqli_close($con);
?>
Here 'invc' is get from httpRequest ,
JSONObject json = jsonParser.makeHttpRequest(url_check_user, "POST", params);
And my JSONParser page contains,
if (method == "POST") {
// request method is POST
// defaultHttpClient
System.out.println("Inside json parser POST condition");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
System.out.println("Inside json parser POST condition" + params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("From httpentity", httpEntity.toString());
System.out.println("ppppppppppppphhhhhhhhhhhhhhhhhhhhppppppppppp");
is = httpEntity.getContent();
}
Now I want to check , whether the parameters were passed to the php page or not. So I want to console/log cat the $invoiceid. How can it possible in Eclipse Ide?
If you want to print a variable inside PHP code, you can do echo $variable. However please note that PHP code will be executed on a server and not on your android device. Moreover your PHP code is vulnerable to sql injection attacks
You can use JSON encoding method in your php file to get a proper JSON response like this.
$response = array (
'invoiceid' => $verify_code,
);
print json_encode($response);
which will return a JSON string to your app in a format like
{"invoiceid":"null"}
which you can decode and log it like this
InputStreamReader isw = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isw);
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null){
buffer.append(line);
}
String finalresult = buffer.toString();
JSONObject myobject = new JSONObject(finalresult);
String flag= myobject.getString("invoiceid");
log.e("mylog",flag)
so that it will be visible in your logcat file.

How to extract json data and insert in mysql php

Actually I am new to android web services so please help me
my problem I am sending json encoded data from mobile client and I am getting json data on server side so that
client side code:
mJobject.put("userName", contactname.getText().toString());
mJobject.put("phonenumber",phonenumber.getText().toString() );
mJArray.put(mJobject);
Log.v(Tag, "^============send request" + mJArray.toString());
contactparams.add(new BasicNameValuePair("contactdetails", mJArray.toString()));
Log.v(Tag, "^============send request params" + mJArray.toString());
jsonString=WebAPIRequest.postJsonData("http://localhost/contactupload/contactindex.php",contactparams);
public static String postJsonData(String url, List<NameValuePair> params) {
String response_string = new String();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
// httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
try {
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String sampleurl = url + "" + paramString;
Log.e("Request_Url", "" + sampleurl);*/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
InputStream in = response.getEntity().getContent();
response_string = WebAPIRequest.convertStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return response_string;
and php side I am doing
<?php
$json_data=$_POST['contactdetails'];
$data=json_decode($json_data);
print_r($data);
?>
I am getting response
Array
(
[0] => stdClass Object
(
[phone number] => 5555
[username] => xfg
)
)
so how can I extract json data in php and insert in mysql
Do somehting like this..
<?php
$json_data=$_POST['contactdetails'];
$data=json_decode($json_data, true); // Added true flag
// You can access your variables like this..
echo $data['phone number'];// prints "5555"
echo $data['username']; // prints "xfg"
//do your db connection...
// execute your query with those variables...
?>
here is a sample code
I assume you know how to parse json from android.
now in your server code use this to get the data from url and insert them to mysql
// check for required fields
if (isset($_POST['location']) && isset($_POST['email']) && isset($_POST['lat']) && isset($_POST['longitude'])) {
$location = $_POST['location'];
$email = $_POST['email'];
$lat = $_POST['lat'];
$longitude = $_POST['longitude'];
require_once 'config.php';
// connecting to mysql
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
// selecting database
mysql_select_db(DB_DATABASE);
// mysql inserting a new row
$result = mysql_query("INSERT INTO marked_locations(location, email,lat,longitude) VALUES('$location', '$email', '$lat','$longitude')");
.....
..
if you have any doughts or have need more help just comment

Posting JSONobjects from android to PHP script

I'm looking to take some data from an android application, post it to a PHP script and then write it into my PostGreSQL database. I'm having some difficulty, could anyone explain why the data is not being transferred. I keep getting a lot of StrictMode violations. I'm hoping that when the user clicks 'Upload' on the app the whole process is automated and the data automatically written to my PGSQL server.
Android application
protected void syncToWebService(final JSONObject json){
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpResponse response;
String httppost = "http://users.aber.ac.uk/dwd/mfb/php/jsonscript.php";
try
{
HttpPost post = new HttpPost(httppost);
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), i);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, i);
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("photo", ba1.toString()));
postParameters.add(new BasicNameValuePair("name", resultName.getText().toString()));
postParameters.add(new BasicNameValuePair("description", resultDescription.getText().toString()));
postParameters.add(new BasicNameValuePair("latitude", resultLat.getText().toString()));
postParameters.add(new BasicNameValuePair("longitude", resultLong.getText().toString()));
postParameters.add(new BasicNameValuePair("project", resultProject.getText().toString()));
postParameters.add(new BasicNameValuePair("owner", username));
//response = CustomHttpClient.executeHttpPost(httppost, postParameters);
post.setEntity(new UrlEncodedFormEntity(postParameters));
response = httpclient.execute(post);
/*Checking response variable*/
if(response!=null){
InputStream in = response.getEntity().getContent();
}
}
catch (Exception e){
e.printStackTrace();
}
}
PHP file
$conn = pg_connect("dbconnection_string");
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!empty($jsonObj)) {
try {
$name = jsonObj['name'];
$desc = jsonObj['description'];
$latitude = jsonObj['latitude'];
$longitude = jsonObj['longitude'];
$project = jsonObj['project'];
$owner = jsonObj['owner'];
}
}
//decode photo string
$photo = $_REQUEST["photo"];
echo $photo;
$binary=base64_decode($photo);
header('Content-Type: bitmap; charset=utf-8');
$id = pg_query("SELECT * FROM users WHERE email = $owner");
$id_assoc = pg_fetch_assoc($id);
$id_res = $id_assoc['u_id'];
$res = pg_query("INSERT INTO records (photo, name, description, latitude, longitude, project, owner) VALUES ('$photo', '$name', '$desc', '$latitude', '$longitude', '$project', '$id_res'");
pg_close($conn);
Any help you can give would be much appreciated.
change this, you missed $ in jsonObj
try {
$name = jsonObj['name'];
$desc = jsonObj['description'];
$latitude = jsonObj['latitude'];
$longitude = jsonObj['longitude'];
$project = jsonObj['project'];
$owner = jsonObj['owner'];
}
to
try {
$name = $jsonObj['name'];
$desc = $jsonObj['description'];
$latitude = $jsonObj['latitude'];
$longitude = $jsonObj['longitude'];
$project = $jsonObj['project'];
$owner = $jsonObj['owner'];
}

Categories