Page 1 of 1

sending from MIDlet, receiving in PHP on server

Posted: Fri Sep 25, 2009 4:17 pm
by johnyjj2
Hello :-)!

I'd like to send text file from MIDlet on mobile phone to PHP on server. I guess there is no difference from PHP point of view whether it is sent from web browser or mobile phone. However if I send it from web browser, I can write:

Code: Select all

<input name="usersfile" type="file">
and in .php file on the server:

Code: Select all

&usersfile = $HTTP_POST_FILES['usersfile']['tmp_name'];
But if I send it from MIDlet:

Code: Select all

HttpConnection conn = null;
String url = "http://87.205.xx.xx/datareceiver.php";
I don't know what to write here:

Code: Select all

&usersfile = $HTTP_POST_FILES['!!!!!HERE!!!!!']['tmp_name'];
I can post the whole code of MIDlet .java file if needed.

The other time is when the .php is executed. I guess it is executed every single time I choose 'send' in my MIDlet. But what to do to avoid using any web-browser on the server? I mean I want the server just to receive the file when it is sent, save it in the proper place, follow some mathematical operations on received data and save it in the database. (At this moment it is only receiving and saving). This is what I've got in datareceiver.php:

Code: Select all

<html>
<head>
    <title> Sending... </title>
</head>
<body>
<h1>File sending...</h1>
<?php
 
$usersfile = $HTTP_POST_FILES['usersfile']['tmp_name'];
$usersfile_name = $HTTP_POST_FILES['usersfile']['name'];
$usersfile_size = $HTTP_POST_FILES['usersfile']['size'];
$usersfile_type = $HTTP_POST_FILES['usersfile']['type'];
$usersfile_error = $HTTP_POST_FILES['usersfile']['error'];
 
if ($usersfile_error > 0)
{
    echo 'Problem: ';
    switch ($usersfile_error)
    {
        case 1: echo 'File size exceeded the value of upload_max_filesize'; break;
        case 2: echo 'File size exceeded the value of max_file_size'; break;
        case 3: echo 'File sent only partially'; break;
        case 4: echo 'No file was sent'; break;
    }
    exit;
}
 
if ($usersfile_type != application/x-www-form-urlencoded)
{
    echo 'Problem: improper file type';
    exit;
}
 
$localization = '/sent/'.$usersfile_name;
 
if (is_uploaded_file($usersfile))
{
    if (!move_uploaded_file($usersfile, $localization))
    {
        echo 'Problem: File cannot be copied to the directory';
        exit;
    }
}
else
{
    echo 'Problem: there could've been attack when sending the file. File name: '.$usersfile_name;
    exit;
}
 
echo 'File sent<br /><br />';
 
$wp = fopen($localization, 'r');
$myContent = fread($wp, filesize($localization));
fclose($wp);
 
echo 'Content of the sent file:<br /><hr />';
echo $myContent;
echo '<br /><hr />';
 
?>
</body>
</html>
Greetings!

Re: sending from MIDlet, receiving in PHP on server

Posted: Fri Sep 25, 2009 6:12 pm
by Mirge
http://androidcommunity.com/forums/f44/ ... ver-25689/
http://www.phpfreaks.com/forums/index.p ... c=270583.0
and here...

You're really trying to get an answer eh? lol

Sorry, I've never used MIDlet.... just found it funny.

Re: sending from MIDlet, receiving in PHP on server

Posted: Sun Sep 27, 2009 5:53 am
by johnyjj2
Hello :-)!

Yeah, I'm really trying to get an answer :D.

Unfortunately I posted my question on more proper forum and there are no answers :-(:
1) http://discussion.forum.nokia.com/forum ... p?t=181006
2) http://discussion.forum.nokia.com/forum ... p?t=181002

There were answers only on two forums - one here and the other one on forum about Symbian, they suggested me to post on forum.nokia.com (no answers).

Even if you don't create MIDlets I am sure just analysing the code by somebody with bigger experience than mine may lead to some conclusions :-).

I am going to repeat my question - but now according to my actual knowledge, summarized and with code of both files :).

In general I'd like to send little text file from MIDlet on mobile phone with the use of httpconnection to server with PHP script.

If it was sent from web browser in PHP file to server with PHP, the sending code would be like this:

Code: Select all

<input name="usersfile" type="file">
and receiving code like this:

Code: Select all

&usersfile = $HTTP_POST_FILES['usersfile']['tmp_name'];
In the case of MIDlet and PHP, sending is like this:

Code: Select all

HttpConnection conn = null;
String url = "http://87.205.xx.xx/datareceiver.php";
and receiving like this:

Code: Select all

&usersfile = $HTTP_POST_FILES['!!!!!HERE!!!!!']['tmp_name'];
In the second case simply I don't know what to write in the place "!!!!!HERE!!!!!".

I guess PHP script is executed on the server every single time I call function sendTextFile on MIDlet, which connects to http://87.205.xx.xx/datareceiver.php.

Second question - I guess much simpler :-). I don't know why there are thos html, body etc. if I don't want any text to be shown on the server with the use of web browser. How to do it, so that script would be executed on the server, would write something to the database and that's all - without showing anything in web browser?

Code of MIDlet, sending data:

Code: Select all

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
 
public class myMidletSendData extends MIDlet
{
    //W tej zmiennej zapisz? obiekt pobrany metod? Display.getDisplay()
    private Display display;    
    
    //Wewn?trzna klasa Ekran rozszerzaj?ca klas? Canvas
    private class Ekran extends Canvas implements CommandListener
    {
        String label = "Tekst domy?lny";//tekst do wypisania na ekranie
        int ScreenWidth, ScreenHeight;  //szeroko?? i d?ugo?? ekranu
        Command opcjawyjscie = new Command("Wyj?cie", Command.EXIT, 1);
 
        //Konstruktor wewn?trznej klasy Ekran
        public Ekran(String inparam)
        {
            //
            label = inparam;
            //Pobieram wysoko?? i szeroko?? dost?pnego ekranu:
            ScreenWidth = getWidth();
            ScreenHeight = getHeight();
            //Dodaj? komend?:
            addCommand(opcjawyjscie);
            setCommandListener(this);
        }
        
        public void commandAction(Command c, Displayable d)
        {
            if (c == opcjawyjscie)
            {
                destroyApp(true);
                notifyDestroyed();
            }
        }
 
 
        /** W matodzie paint() definiujemy wygl?d elementu
        */        
        protected void paint(Graphics g)
        {
            //Namalowanie t?a:
            g.setColor(0xffffff); //zmiana aktualnego koloru
            //Namalowanie wype?nionego aktualnym kolorem prostok?ta:
            g.fillRect(0, 0, ScreenWidth, ScreenHeight);    
            //Wspó?rz?dne w rogach ekranu:
            g.setColor(0x000000);
            g.drawString("(0,0)", 0, 0, g.TOP|g.LEFT);
            g.drawString("(" + ScreenWidth + "," + ScreenHeight
                + ")", ScreenWidth, ScreenHeight, g.BOTTOM|g.RIGHT);
            //Tekst na ?rodku ekranu:
            g.setColor(0x770000);
            g.drawString(label, ScreenWidth/2, ScreenHeight/2,
            g.HCENTER|g.TOP);
        }
    }
 
    public myMidletSendData() //konstruktor MIDlet-u
    {
        try {
            sendTextFile("123456789012 234567890123 end");
        }
        catch (IOException e) {
            System.out.println("IOException " + e.toString());
        }
    }
 
    public void startApp() {
        display = Display.getDisplay(this);
        display.setCurrent(new Ekran("Witaj w aplikacji!"));
    }
 
    public void pauseApp() {
    }
 
    public void destroyApp(boolean unconditional) {
    }
 
    public void sendTextFile(String name) throws IOException
    {
        System.out.println("Wywolano sendTextFile");
 
 
        HttpConnection conn = null;
        String url = "http://87.205.18.184/datareceiver.php";
        String agent = "Profile/MIDP-1.0 Configuration/CLDC-1.0";
        String rawData = "vagons=" + name;
        String type = "application/x-www-form-urlencoded";
 
        //String encodedData = encode( rawData ); // user-supplied
        String encodedData = rawData; //z powodu bledu kompilacji nie bede
        //kodowal rawData - kodowanie rzekomo potrzebne z powodu typu x-www-form-urlencoded
    
        try {
            conn = (HttpConnection) Connector.open( url );
            conn.setRequestMethod( HttpConnection.POST );
            conn.setRequestProperty( "User-Agent", agent );
            conn.setRequestProperty( "Content-Type", type );
            conn.setRequestProperty( "Content-Length", "encodedData.length()" );
            //http://forum.vingrad.ru/act-Print/client/html/f-114/t-185266.html <- wziac w cudzyslow
    
            getConnectionInformation(conn); //pozniej mozna usunac to
            //wywolanie jak i sama funkcje getConnectionInformation
    
            OutputStream os = conn.openOutputStream();
            os.write( encodedData.getBytes() );
        
            int rc = conn.getResponseCode();
            // ... process it
            //System.out.println("ResponseCode " + rc.toString());
            //powyzej wyskakiwal blad: int cannot be dereferenced
            System.out.println("ResponseCode " + rc);
 
        }
        catch( IOException e ) {
            // handle the error here
            System.out.println("IOException " + e.toString());
        }
        //wyrzucilem finally bo bylo za duzo bledow kompilacji w zwiazku z is oraz conn
 
 
    }
 
    /***  After setup, attributes of the HttpConnection object can be retrived using
        various get methods.
    ***/
    void getConnectionInformation(HttpConnection hc) {
        System.out.println("POCZATEK GET CONNECTION INFORMATION");
        System.out.println("Request Method for this connection is " + hc.getRequestMethod());
        System.out.println("URL in this connection is " + hc.getURL());
        System.out.println("Protocol for this connection is " + hc.getProtocol()); // It better be HTTP:)
        System.out.println("This object is connected to " + hc.getHost() + " host");
        System.out.println("HTTP Port in use is " + hc.getPort());
        System.out.println("Query parameter in this request are  " + hc.getQuery());
        System.out.println("KONIEC GET CONNECTION INFORMATION");
    }
}
Code of receiving PHP:

Code: Select all

//datareceiver.php:
 
<html>
<head>
    <title> Wysylanie... </title>
</head>
<body>
<h1>Wysylanie pliku...</h1>
<?php
 
$plikuzytkownika = $HTTP_POST_FILES['plikuzytkownika']['tmp_name'];
$plikuzytkownika_name = $HTTP_POST_FILES['plikuzytkownika']['name'];
$plikuzytkownika_size = $HTTP_POST_FILES['plikuzytkownika']['size'];
$plikuzytkownika_type = $HTTP_POST_FILES['plikuzytkownika']['type'];
$plikuzytkownika_error = $HTTP_POST_FILES['plikuzytkownika']['error'];
 
if ($plikuzytkownika_error > 0)
{
    echo 'Problem: ';
    switch ($plikuzytkownika_error)
    {
        case 1: echo 'Rozmiar pliku przekroczyl wartosc upload_max_filesize'; break;
        case 2: echo 'Rozmiar pliku przekroczyl wartosc max_file_size'; break;
        case 3: echo 'Plik wyslany tylko czesciowo'; break;
        case 4: echo 'Nie wyslano zadnego pliku'; break;
    }
    exit;
}
 
if ($plikuzytkownika_type != application/x-www-form-urlencoded)
{
    echo 'Problem: plik nie jest odpowiedniego typu';
    exit;
}
 
$lokalizacja = '/wyslane/'.$plikuzytkownika_name;
 
if (is_uploaded_file($plikuzytkownika))
{
    if (!move_uploaded_file($plikuzytkownika, $lokalizacja))
    {
        echo 'Problem: Plik nie moze byc skopiowany do katalogu';
        exit;
    }
}
else
{
    echo 'Problem: mozliwy atak podczas wysylania pliku. Nazwa pliku: '.$plikuzytkownika_name;
    exit;
}
 
echo 'Plik wyslany<br /><br />';
 
$wp = fopen($lokalizacja, 'r');
$zawartosc = fread($wp, filesize($lokalizacja));
fclose($wp);
 
echo 'Podglad zawartosci wyslanego pliku:<br /><hr />';
echo $zawartosc;
echo '<br /><hr />';
 
?>
</body>
</html>
I posted my question on the other forum and there were no answers :-(. I guess the only one hope for my is this forum (or Symbian forum) and your help :-).

About MIDlet: I think just analysing this code, without your knowledge about MIDlet may be great help. In general in MIDlet there are three functions - startApp, pauseApp and destroyApp, which are responsible for basic life-cycle of MIDlet. There is also - of course - constructor, in this case it just calls function responsible for sending examplary string to server. In other words - the only one important thing in MIDlet is function sendTextFile.

Thanks very much for your help in advance!
Greetings :-)!

Re: sending from MIDlet, receiving in PHP on server

Posted: Sun Sep 27, 2009 8:14 am
by ell0bo
I'll see how much I can help you here. I once wrote an applet that would allow people to drag and drop folders from their desktop onto it to upload files. Parts of that can be used to help you out right now. Note, this is from at least two years ago, and I was brute forcing my way through the problem, but it should help. I also noticed you're using the wrong header info if you're trying to send a file in a post stream...

public class Uploader implements Runnable{
private LinkedList Elements;
private String Target;
private String Name;
private String Code;
private String Label;
private ActionListener CB;

public static final int DATA_SENT = 1;
public static final int DATA_RETURNING = 2;
public static final int ALL_DONE = 3;

public Uploader(String t, String n, String c){
Target = t;
Name = n;
Code = c;

Elements = new LinkedList();
}

public void addFile(String n, String path){
Elements.add(new FormFile(n,path));
}

public void addVar(String n, String var){
Elements.add(new FormVar(n,var));
}

private void sendData(DataOutputStream dos) throws IOException{
Iterator i = Elements.iterator();
while(i.hasNext()){
((FormType)i.next()).printContent(dos);
}
}

public void init(){
}

public void submit(ActionListener callBack, String l){
Label = l;
CB = callBack;
new Thread(this).start();
}

public void run(){
try{
URL u = new URL(Target);
URLConnection c = u.openConnection();
// post multipart data
c.setDoOutput(true);
c.setDoInput(true);
c.setUseCaches(false);
// set some request headers
c.setRequestProperty("Cookie", "vName="+Name+";vCode="+Code);
c.setRequestProperty("Connection", "Keep-Alive");
c.setRequestProperty("HTTP_REFERER", "http://applet.getcodebase");
c.setRequestProperty("Content-Type", "multipart/form-data; boundary="+FormType.boundry);
DataOutputStream dstream = new DataOutputStream(c.getOutputStream());
// write content to the server, begin with the tag that says a content element is comming
dstream.writeBytes("--"+FormType.boundry+"\r\n");

sendData(dstream);

dstream.writeBytes("\r\n--"+FormType.boundry+"--\r\n\r\n");
dstream.flush();
dstream.close();
CB.actionPerformed(new UploaderEvent(this, DATA_SENT, Label, "Sent"));
try{
InputStreamReader Reader =
new InputStreamReader(
new BufferedInputStream(c.getInputStream()));

BufferedReader File = new BufferedReader(Reader);
String Line;
while ((Line = File.readLine()) != null){
CB.actionPerformed(new UploaderEvent(this, DATA_RETURNING, Label, Line));
}
File.close();
CB.actionPerformed(new UploaderEvent(this, ALL_DONE, Label, "Done"));
}catch(Exception e){
e.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}
}
}


and then it's run by this....

LinkedList files = fTree.getFileNodes();
Uploader u = new Uploader(SERVER, USER, PASSWORD);

u.addVar("who",FOR);
u.addVar("method","fileDo");
u.addVar("type","add");
u.addVar("count",""+files.size());
u.addVar("folder", folder.getText());

for (int i = 0; i < files.size(); i++){
FileTreeNode file = (FileTreeNode)files.get(i);
u.addFile("file"+i,file.getFilePath());
u.addVar("name"+i, file.getFileName());
}

log("Uploading files...");
u.submit(this, FUPLOAD);

that should be able to help you out I do believe. If not, let me know.

Re: sending from MIDlet, receiving in PHP on server

Posted: Mon Sep 28, 2009 2:02 pm
by johnyjj2
Thanks very much for your answer :-)

I guess I should try to change this code which you posted here to meet my requirements :-). But at this moment I thought about something else - http://codetrips.blogspot.com/2007/04/h ... idlet.html .

I've got server with really bad configuration (I am not admin) - PHP, Apache, IIS, KeyFocus Web Server. I guess this all works together properly (or rather not quite, because I've got some difficulties with configuring PHP).

Is it good idea to install this Apache Tomcat if I've already got Apache? Is this Apache Tomcat something like extension for Apache? I know it is servlet container but I don't need any other application if I've got already some of them which may, probably, be used to execute that servlet which is here: http://codetrips.blogspot.com/2007/04/h ... idlet.html .

Greetings :-)!