PHP - Receive Json (POST) - php

I am sending a Json array to server :
{
"Name":"Number",
"Name":"Number"
, ...
}
How can i receive it on PHP ?
Send method is POST .
Here is my android code :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.7/admina/contacts_inout.php");
String json = "";
json = jsons.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);

Since PHP only handles POST-data which is application/x-www-form-urlencoded or multipart/form-data formatted, you'll have to use the RAW input
use
$sent_array = json_decode(file_get_contents('php://input'),true);
to get the data as an array

isset($_POST['your_param_key']) or exit('param not found.');
$json = $_POST['your_param_key'];
$array = json_decode($json, true);
print_r($array);

Related

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.

Post request receives null value

I am developing a software wherein I send a post request to server (which is written in PHP) but the server receives null value. Any help would be appreciated.
Android and PHP files enclosed.
**This is my Android file:**
public static JSONObject tosend = new JSONObject();
for(int i=0;i<3;i++)
{
JSONObject jo = new JSONObject();
jo.put("infoName", infoName[i]);
jo.put("infoNumber", infoNumber[i]);
jo.put("direction",direction[i]);
jo.put("version",version[i]);
JSONArray ja = new JSONArray();
ja.put(jo);
tosend .accumulate("introduceesJson", ja);
}
String link = "http://172.65.45.7/checkAppInstalled.php";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(link);
StringEntity se;
se = new StringEntity(tosend.toString());
// Set HTTP parameters
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "*/*");
httpPostRequest.setHeader("Content-type", "*/*");
//httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
//long t = System.currentTimeMillis();
/* HttpPost httpPostRequest = new HttpPost(link);
List<NameValuePair> nVP = new ArrayList<NameValuePair>(2);
nVP.add(new BasicNameValuePair("json", tosend.toString()));
httpPostRequest.setEntity(new UrlEncodedFormEntity(nVP));*/
//Log.e("Posted data", "TestPOST - nVP = "+nVP.toString());
// Hand the NVP to the POST
Log.e("posted data",tosend.toString());
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
String jsonReceived = EntityUtils.toString(entity);
Log.e("result received",jsonReceived);
}
Here's my PHP code:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
if(!empty($jsonObj)) {
foreach($jsonObj as $json){
echo $json['infoName'];
echo $json['infoNumber'];
echo $json['direction'];
echo $json['version'];
}
}
else
{
echo "json empty";
}
Here is the logcat result:
04-02 15:34:07.882 9526-9704/com.thoughtrix.introduce E/posted data﹕ {"introduceesJson":[{"infoName":"Aa","direction":"2","version":"1","infoNumber":"96 35 874125"},[{"infoName":"Aa","direction":"2","version":"1","infoNumber":"96 35 874125"}]]}
Result Received : json empty.
Dont know much from json but fiddled around a bit: Try this:
var_dump($jsonObj['introduceesJson']);
$jsonArray = $jsonObj['introduceesJson'];
foreach($jsonArray as $json)
{
echo("------\n");
var_dump ($json);
foreach ( $json as $jsonarray )
{
echo(" ------\n");
var_dump ($jsonarray);
echo $jsonarray['infoName'];
echo $jsonarray['infoNumber'];
echo $jsonarray['direction'];
echo $jsonarray['version'];
echo ("\n");
}
} –
Could you please post the complete php script to extract all variables when you are done? I was puzzled...

sending a value with HttpPost object

I would like to send a value to the end of a url.
ex:
if I have id=1;, I want to send this id to end of my url (to obtain id) :
www.example.com/get/id
id values ​​are different. (ex:id=2;id=3;id=4...).
is it possible ? how can I use HttpPost for this Scenario ?
I am using these functions but I always get this message :
no parametrs was sended !
inside my url :
www.example.com/get/id :
function get($id=0){
$id = (int)$id;
if(!$id) exit("no parametrs was sended !");
$trac = $this->m_general->get('tractions' , array('id' => $id ) , true );
if(!$trac ) $resp = "-1";
else
if($trac->expired != 0 || $trac->cradit_end_date < date('Y-m-d'))
{
$resp = 0;
}else
$resp = 1;
echo json_encode(array('response'=>$resp));
}
function set(){
$data = $this->input->post('data');
if(!$data) exit("no parametrs was sended !");
$message = $data;
$message = substr($message,7,-6);
list($qr,$date,$time) = explode("&",$message);
$insert = array(
'qr'=>$qr ,
'date'=>$date ,
'time'=>$time ,
'main'=>$message
);
$this->m_general->add('qr' , $insert );
}
private void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url_server_side);
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
String res = EntityUtils.toString(response.getEntity());
Log.e("Response = ", res);
isok = 1 ;
} catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
} catch (IOException e) {
e.printStackTrace();
// TODO Auto-generated catch block
isok = -1 ;
}
//Log.e("res", response.toString()) ;
}
As you mentioned above your web application expecting GET method to pass variables. In java code you are sending a POST request. You should use GET method to pass data.
String url = "http://www.example.com/id/YOUR_ID_DATA/data/YOUR_DATA";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Or send both id, data in a POST request and accept as a POST response from PHP side.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
HttpResponse response = null;
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", YOUR_ID_DATA));
nameValuePairs.add(new BasicNameValuePair("data", YOUR_DATA));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Then in PHP Side
$id = $_POST["id"];
$data = $_POST["data"];

Android post Base64 String to PHP

------ Solution ------
The issue was on our server. It can only handle post requests if we put www in front of our domain name. So that's what caused the problems. I'm setting the first answer as THE answer since it worked once I sorted the URL out.
Original Question
I have a POST variable in my PHP script is always blank.
I've tried to change the variable's name, the content of the variable etc..
The problem has to reside in the java code, because when I var_dump() the request in php, it is null.
This is my scenario:
I let the user snap a photo, the photo is saved to the SD-card and I get the image's path, and eventually convert it to a Base64 string. I then want to post this base64 string to a php script that converts it back from Base64 and writes it as an image on my server's hard drive like so:
File f = new File(savedImagePath);
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://myURL/uploadImage.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("image", image_str));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
On the server end, this is what my PHP script looks like:
<?php
$base = $_POST["image"];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('uploaded_image.jpg', 'w');
fwrite($file, $binary);
fclose($file);
echo "script done executing";
?>
This is an example of a Base64 string I'm trying to post:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABsSFBcUERsXFhceHBsgKEIrKCUlKFE6PTBCYFVlZF9VXVtqeJmBanGQc1tdhbWGkJ6jq62rZ4C8ybqmx5moq6T/2wBDARweHigjKE4rK06kbl1upKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKT/wAARCAogBsADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFD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dJSigVw70d6QUtAw9zzRSZpc5+tMVwNL7UlH40gCgdaUcUlMApRRR2oAPeiijPFAIBQOtFFAbCikozRQADmlpBS0DAUUnfNL3oEFAo7YoxTAXvSdqO+BzR9KAClHWkooBB0paM0UgFpBSdTQPrmgQtHWjPOaO9MBc0Ug60A0guFLRSUDQUUfSimAtJ3oo70gFzRSUZoAWkozR+lMOgtFJR1oAXNHSkFFAC0dqQdKM0gFopB15oPWmAtA60maO1AIWj8KQUUBYX9aKQGigA9qKM0d6QCig0lFAgo60DpRQMO1ITRmk7UCEprdKcaQ0DGGoyKeaY3ftSAYSKhbpUp7d6jbmkxoiPFN7U5vu9aYeKQx38OR0pU9qb29q
This is the code for image:
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
This is the HTTP code for sending the image to the server:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://servername.com/uploadimage.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
If you find any more difficulties ask me or a check:
this similar tutorial for image uploading
Base64 example
In PHP header file changes :
header('Content-Type: image/jpg; charset=utf-8');
$base=$_REQUEST['image'];
Have you tried reading the raw post data in PHP? Something like
$data = $xml = file_get_contents('php://input');
Have a look at this link for more info
http://www.codediesel.com/php/reading-raw-post-data-in-php/
just download the Base64.java http://iharder.sourceforge.net/current/java/base64/ & put that file in your project & then
just replace the
String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
this with
String image_str = Base64.encodeBytes(byte_arr);
replace this post.setEntity(new UrlEncodedFormEntity(pairs));
with
post.setEntity(new UrlEncodedFormEntity(pairs,HTTP.UTF_8));
Also check while importing the Base64 it will import file from your package & then post to server it will post.
in your php code just change
change this
$base = $_POST["image"];
to
$base = $_REQUEST['image'];
Try sending your data as below:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 60000); //1 min
HttpConnectionParams.setSoTimeout(httpParams, 60000); //1 min
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost("http://myURL/uploadImage.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("image", image_str));
post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); // as UTF-8
HttpResponse response = client.execute(post);
Is the HTTP-Response-Code you are getting 200?
If so, try setting these header-fields:
"Accept": "text/html"
"Accept-Language": "en"
"Content-Length": yourString.length
"Content-Type": "application/x-www-form-urlencoded"

HTTP post from android to PHP not working

I am trying to get a Android device to send some information to a local host. I believe I have the Android sending the information, but my PHP code is not accepting or not displaying the code. I have attached my code, is there something I have missed? I am running wamp server also, and have put the permissions into the manifest.
Java Code: #
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("parameterName1", "git"));
nameValuePairs.add(new BasicNameValuePair("parameterName2", "git"));
// Send POST message with given parameters to the HTTP server.
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}
PHP Code:
<?php
echo "param1 value: ".$_POST['parameterName1']."\n";
echo "param2 value: ".$_POST['parameterName2']."\n";
?>
I also tried this code, but it did not work with my PHP
HttpPost httppost;
HttpClient httpclient;
// List with arameters and their values
List<NameValuePair> nameValuePairs;
String serverResponsePhrase;
int serverStatusCode;
String bytesSent;
String serverURL = "http://10.0.2.2/test/index.php";
httppost = new HttpPost(serverURL);
httpclient = new DefaultHttpClient();
nameValuePairs = new ArrayList<NameValuePair>(2);
// Adding parameters to send to the HTTP server.
nameValuePairs.add(new BasicNameValuePair("'parameterName1'", "git"));
nameValuePairs.add(new BasicNameValuePair("'parameterName2'", "git"));
// Send POST message with given parameters to the HTTP server.
try {
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bytesSent = new String(baf.toByteArray());
// Response from the server
serverResponsePhrase = response.getStatusLine().getReasonPhrase();
serverStatusCode = response.getStatusLine().getStatusCode();
System.out.println("response" + response.toString());
System.out.println("COMPLETE");
} catch (Exception e) {
// Exception handling
System.out.println("Problem is " + e.toString());
}
Make sure the Content-Type HTTP header is getting set. Try replacing
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
with this
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
httppost.addHeader(entity.getContentType());
httppost.setEntity(entity);
Also, instead of response.toString(), try EntityUtils.toString(response.getEntity()) if you want to see the body of the response

Categories