how to make PHP server sends data to an Android device - php

I want the Android device to send data to a PHP server. After receiving, the PHP server sends other data to Android. The first part can be done by using JSON. However, I don't know how to make the PHP server sends data to Android. Sorry, I am new to PHP!

I'm currently developing application that's communicating with PHP server (two-way communication, server sends data to application and application sends data to server), in objective-c [for iphone], but principle is same I guess.
We've used REST service with JSON.
In your case, it should work like this:
Mobile 1 sends data via REST call to REST server (it calls method1. Server is developed, for example, using Zend_REST.), it stores data in Database (mySQL for example).
Mobile 2 periodically sends request to REST server, to a method which checks for new entries in mySQL. If there's something new, it sends response with data, if not - it sends false.

Whatever data is "printed" by your PHP script will be returned in the response to the call made on the Android device.
You can do something like this in PHP:
<?php
// TODO: Handle incoming data
// Send JSON data back to client
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// Compute data
$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Encode/print data
echo json_encode($data);
?>
You would want to replace the first comment with your code to handle the data that was submitted from the client (Android). Then you set the response headers to be of type application/json and echo back your encoded data.
Technically you could echo/print back anything you would like, but using a format like JSON makes it much easier to decode the data on the client side.

Here is an Android snippet to send a POST request to some bogus website, sending email, password and a data string (you would put your json in the data string
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://website.com/yourPageHere.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", emailString));
nameValuePairs.add(new BasicNameValuePair("password", passwordString));
nameValuePairs.add(new BasicNameValuePair("data", yourDataString));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
//do stuff
}
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
//do stuff
} catch (IOException e) {
//do stuff
}
if(response == null){
//time out or other problem, fail gracefully
}
HttpEntity responseEntity = response.getEntity();
try {
String jsonString = EntityUtils.toString(responseEntity);
//jsonString is the full body of the response from the server
//if your php script is sending json, thats whats in here
} catch (ParseException e) {
//do stuff
} catch (IOException e) {
//do stuff
}
Your php script, yourPageHere.php
Treat this just like any other php script you might write, except instead of returning html you are just returning a chunk of text representing json data.
<?php
header('Content-type: application/json');
/*
here you can use the $_POST['email'], $_POST['password']
and $_POST['data'] indexes to access the data sent to
you from the phone, then create a json string to return
to the phone
*/
/* you can convert php objects/arrays to json using
json_encode($object), handle this however you
want just so that $jsonString is the final
representation of the json object */
$jsonString = 'blabla';
/*
prints the string in the body of the response,
this is the "jsonString" object found in the
above android snippet.
*/
echo $jsonString; //
?>
You can do the above with GET requests instead of POST too.
If you are really new to PHP you might want to make a couple form page samples to get the hang of reading url parameters.

What you're looking for is some sort of AJAX call, allowing the HTTP GET request to stick around and wait for the server return value:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Related

How to communicate from php to Android

I am making a location application, where user can parameter some function from the server, so I want the server to begin a communication with the phone of the user.
But firstly, I want to open a communication with an android, from the php.
Is there a way to communicate with an android phone from a php server?
I already use the communication from android with HTTP to server with return of JSONObject, but I cant find anything for a php call to android.
I think its exactly like the application which can make your phone ring.
Check out Google Cloud Messaging for Android.
Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device. This could be a lightweight message telling your app there is new data to be fetched from the server (for instance, a movie uploaded by a friend), or it could be a message containing up to 4kb of payload data (so apps like instant messaging can consume the message directly).
The GET method
You will need to have the Android client connect to your server and pass your JSON messages. If the client needs to get some data from the server and disconnect, then you can just use a normal HTTP type GET.
The WebSocket method
If however, you decide you need a long running TCP connection passing JSON bidirectionally then you should consider something like WebSockets. I have written an Android WebSocket demo. The Android client by default connects to the websocket.org echo server, but that can be easily changed.
I also found a PHP WebSockets implementation.
The Push Method
Now if your plan is to push messages from the server to the client without the client initiating the connection you will need something like GCM (Google Cloud Messaging). Here is an article covering GCM and PHP.
Generally, creating connection from server side to client side is complex, because:
The client might use private IP address.
Inbound connection might be rejected if the device connected behind firewall.
You need to install an application if that can be run in the background and watches the server for new messages.
Using Web:
It depends on the browser how it support JavaScript API especially new HTML5 features such as Server Sent Events
To enable servers to push data to Web pages over HTTP or using
dedicated server-push protocols, this specification introduces the
EventSource interface.
Please use below link for store data in mysql using php and u need to create webservice in that you will get two response from php server
1) Json
2) xml
if you show example please visit below link
Creating a basic web services in php
also visit this link for better description
http://phpmaster.com/lets-talk-1/
You Can Use HTTpReq class :
public class HttpReq {
public String send (String url){
//send a http request and get the result
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
}
Then you use this class to make connection and to call your php file to get the data as JSonObject .
ht = new HttpReq();
// send a http request with GET
x=ht.send("http://10.0.2.2/myFolder/myFile.php");
JSONArray jArray;
JSONObject json_data;
String h[]=x.split("<");
try {
jArray = new JSONArray(h[0]);
json_data = jArray.getJSONObject(0);
url=json_data.getString("url");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In Your Php file you may use this methods to get the JSon data or to send it to the android App
Json_decode($string);
And
Json_encode($string);
I hope that will help you :)

Write new mysql rows based on certain number of php responses/information passed

In my android application, I am querying a mysql database for a specific food id.
Example:
Food A - (food_id 5)
Food A is part of three food groups, each with their own unique ID.
Example:
Meal A - (meal_id = 3),
Meal B - (meal_id = 8),
Meal C - (meal_id = 20)
I am currently connecting to the mysql database via php, and can successfully query for the food_id in question and receive the JSON response into my android application.
I am stuck how to then pass it back through php/JSON to create three mysql rows (one for each meal returned) which will include some extra information added onto it in some new fields. Would I best be served by passing an array from android to my php service? How would this look?
Just use an HttpClient to make a request back to the PHP application endpoint where you want to handle the incoming data, POSTing the data you want to work with on the server. You can post in whatever format suits you - query string, JSON, etc.
You can send data to your PHP files using HTTPClient
Here's a quick example:
url = "http://10.0.218.211/post.php";
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("meal1", "important message 1"));
nameValuePairs.add(new BasicNameValuePair("meal2", "important message 2"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
post.php
<?php
$meal1 = $_POST['meal1'];
$meal2 = $_POST['meal2'];
?>
It sounds like you need to design some sort of API. The typical options are implementation of SOAP or REST. As SOAP has a lot of overhead, you could alternatively create a REST interface to your system. I'm just guessing, but an API call like this might make sense:
POST /user/meal
With a form that would include form fields for:
userId - the id of the user to create the meal plan for
meals - a comma delimitted list of the meals, or alternatively an array element
Your PHP script would simply need to get the POST params from $_POST, insert the appropriate rows, and return a valid HTTP status code.

How to make a web service (preferably using PHP) that can be requested to get JSON objects by the android app

I am making an Android App which interacts with remote server's database and communicate with each other by passing JSON object to and from.
I need to know how to write such a service on my server (preferably in PHP) to which the android app can make request and on receiving the request, the server processes and makes a JSON object and passes that to the android app.
Also, i need to know, when this service is running on the server, on WHICH URL will the android app make request?
For example, if android app have to request to sever to fetch data for parameters:
name: Apple
location: US
then, i guess the android app will have to request the server in form of:
www.example.com?name='Apple"&location='US'
So how to make such a service running on the remote server?
Thanks in advance !
The best example you can refer for this is http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/. It has complete code[php+ android] with simple explanation.
You can write a method that request remote php file that responses to post or get request. if you want to use post request , you can use method below. and you have to add Internet permisson to your manifest file. As you see below , you can add parameters as being key -value pair.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/webservice.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", "Apple"));
nameValuePairs.add(new BasicNameValuePair("locaction", "US"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler <String> res=new BasicResponseHandler();
// Execute HTTP Post Request
String response = httpclient.execute(httppost,res);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

Sending information from android app to a php script

I'm neither a android or php expert, the thing is that I made a php script that gets the variables from the url ( www.myhost.com/mailScript.php?variable1=name&variable2=age ) and sends a mail with that information.
Mail:
Variable1=Name
Variable2=Age
Now, the problem is that i'm makin a android app that converts a normal form, which ask name, age, etc. And i want to take that information and run php script. But i dont want the users to see a web browser at any time, just that they click de button, get the info, run the url, and done.
The easiest way to do it is mentioned here. Basically, you just want to form the URL based on the value of each of your fields, then hit that URL with an HTTP request.
Use JSON to send data to your PHP script.
By combining that
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Source : http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
and looking about JSON, you should be able to do what you want
your php will be the server side and your android application will the be the client side you will just create a form using normal android's UI widgets. There's a plenty of examples around and send your data via HttpPost or HttpGet classes with your parameters set from this form.
http://mobile.tutsplus.com/tutorials/android/android-sdk-creating-forms/
and posting example Secure HTTP Post in Android

How to use BLOB with JSON and PHP?

I have a remote database with MySQL, and I am storing photos of the users of my app on the database as a row of the database with LONGTEXT type.
I transform the photos to a string with Base64.
I connect to my remote database with JSON and PHP, because this, I have to use Base64, because as I know, JSON and PHP need to send strings on the parameters, and with Base64 I can transform the photo into a string.
It works ok, but it's very slow. When I am loading a photo of 100 KB, it takes a lot of time, but when I am loading a photo of 5 KB it takes only two or three seconds.
A friend told me to use BLOB instead of Base64, but how do I use BLOB with JSON and a PHP connection to the database? Also, I need to store the images on a row of the table USER. This is because the users don't have privileges to upload files into the remote server, but they can upload photos by uploading them as a string in a row of the table USER.
thanks
EDIT:
this is the code where it takes a looot time waiting (it waits in the line: while ((line = reader.readLine()) != null) { , it is waiting on reader.readLine() )
this code gets one user from the remote database, it takes a loooooot of time to show the user on my app
public Friend RetrieveOneUser(String email)
{
Friend friend=null;
String result = "";
//the parameter data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email",email));
//http post
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.BaseURL + this.GetOneUser_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
friend=new Friend(json_data.getString("email"),json_data.getString("password"), json_data.getString("fullName"), json_data.getString("mobilePhone"), json_data.getString("mobileOperatingSystem"),"",json_data.getString("photo"));
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return friend;
}
Segment the request into two parts:
First downloads the JSON with everything except the image, return a reference to the image as a URL instead
Second download the image as a binary chunk, potentially asynchronously depending on the app
I'm assuming you have something like http://example.com/userinfo/xxx as an endpoint that returns the JSON? Add an endpoint like http://example.com/userinfo_image/xxx to return just the image, then you can return it as a binary chunk instead of Base64 encoding it in the JSON.
It means you make two HTTP requests instead of one, but depending on the app you might be able to do the image load asynchronously, and if so you normally get a big gain in perceived application response time from the users perspective.
For info about lazy loading images in the background see the post on the Android Developers blog for a sample:
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
If you can't lazy load the image consider doing parallel requests for both the image and the JSON at the same time. With the binary version of the image taking a lot less network bandwidth, and a lot less processing once you get the data onto the handset, it should still seem a lot more speedy.
Why not dump your image as a file on the server and return the url of the written file in your json? This is really how you should do what you want to do since http is the protocol you should use for transfering images over the web.
Code similar to this should do what you want on the server
//code to get your row from database
//Code that writes it to a file.
$Data = $row['myblobfield'];
$fp = fopen('myimgname.jpg', 'w');
fwrite($fp, $Data);
fclose($fp);
This will write your blob or longtext fields as a file on your server which you can then download from your mobile app. You can then delete this temp files after an interval.
Hope this is useful
To answer your question:
No, JSON doesn't support binary data, you must escape it in some way before sending it. Storing it as BLOB in MySQL is not going to fix the major infrastructure issues you have.
From what I understand you have an Android device that is uploading a picture to a PHP server, this PHP server is encoding the picture to Base64, putting that into a JSON string and then posting it to a remote(how remote is remote? same data center? across the country? across the world? in outer space orbiting the moon?) MySQL server through an HTTP interface of some sort, that MySQL server is storing the Base64 image as LONGTEXT. To get the image back, the Android Client sends a request to PHP, PHP sends a request to the remote MySQL server, PHP then has to Base64 decode the image and send it down.
This is horribly inefficient, you are going to suffer latency every step of the way.
Edit: okay it looks like this is a client side issue and not a server side issue...
If that's the case then I'd suggest checking the posts # Uploading images to a PHP server from Android as they should have some more efficient examples.
Is the slowness coming from json/base64 encoding 100K of data, or from the database hit? Its probably from the encoding, and putting the files in the file system (as everyone in the comments is crying), on a small scale, is not going to make a bit of difference.
Do some measurements on the different parts of the operation, and try to pinpoint why its slow. I don't know how else you'd get an image blob into a json encoded string without base64, i suppose you could try and escape everything, which might be just as slow, and hope the parser doesn't choke on it.
Are you using the json_encode function in php, or manually building the string? Try building it manually. Are you base64 encoding raw data from the database, or is it encoded before its stored, you should encode it before its stored to save time when outputting.

Categories