How to use BLOB with JSON and PHP? - 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.

Related

Android - How to export database content to csv using PHP

I have a MariaDB database where I insert data via a php file by making a post request.
I now want to retrieve all the database content via PHP in the form of CSV.
I've found a PHP file that downloads the database content as csv and it works.
This is the code I had at first:
String url = allConstants.BASE_URL + "exportData.php";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
The above code works but it opens up momentarily the browser and then the file is downloaded. I don't want that to happen. I want the file to be downloaded in the background without opening anything.
I have also tried using Async task and making a post request.
#Override
protected String doInBackground(String... params)
{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(allConstants.BASE_URL + "exportData.php")
.method("GET", null)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
try
{
response = client.newCall(request).execute();
} catch (IOException e)
{
e.printStackTrace();
}
Log.i(TAG, "reresponse: " + response);
return null;
}
The above code seems to execute the PHP file, but no csv file is downloaded on device.
What modifications are needed for the above code in order to work?
Do I need to save the database content to a variable first and then save it to the user's device? If that's the case, I don't see why, since the PHP file does exactly that.

How to get an Image file from PHP and show in Android? [duplicate]

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.

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 :)

Use database for Android App by downloading with php-script

I'm going nuts! Maybe someone can help me?!
I have an sqlite-database on a running server, which I receive due to an php-script. (To make it clear: I'm calling an php-script which gives me the the database as a response). With the response I'm now trying to "parse" it to an regular *.db file which I later on use for my app.
the app works fine, while placing the *.db into the assets folder. But I need to get the updated database everytime when calling the app. Therefore I need to receive it somehow from the server.
Just for notice: I don't know why they use a php-script for that, but it works perfectly with the iOS-Version of the app. So I am 100% sure that the script does work.
Got any hints or a solution to that?
Thanks!
EDIT: here is what I'm trying to do.
private void copyDatabase() {
InputStream myInputDB = null;
OutputStream myOutputDB = null;
HttpResponse response = null;
// Path to the just created empty db
String dbFilePath = DB_PATH + KeyConstants.DB_NAME;
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://USERNAME:PASSWORD#ADRESS/u/db.php");
try {
response = httpClient.execute(httpPost);
//Open your local db as the input stream
myInputDB = response.getEntity().getContent();
//Open the empty db as the output stream
myOutputDB = new FileOutputStream(dbFilePath);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInputDB.read(buffer)) > 0){
myOutputDB.write(buffer, 0, length);
}
//Close the streams
myOutputDB.flush();
myOutputDB.close();
myInputDB.close();
} catch (IOException ioEXC) {
throw new Error("Problem copying database from resource file.");
}
What do You have the problem with? With the Android app or with the PHP script?
I don't understand why there is a whole DB file request-response and not just the data (and better in some lazy reading), but that's not matter of Your case.
If You need to "download" all the DB at every run You should call and implement some method to do so - in the very first Activity call this method within onCreate() method. You can create a simple method within this Activity or in better approach create a simple class for this that will be instanciated and its method called within the first activity's onCreate().
But maybe I just don't understand You question...
EDIT: try reading through this problem: Can I download an SQLite db on /sdcard and access it from my Android app?

how to make PHP server sends data to an Android device

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/

Categories