Using session with php and Java

I'm currently trying to use the current php webpage session from an applet. I would say that it would be simple, but it was not as smooth as me. From php man :

session_start() creates a session or resumes the current one based on a session
identifier passed via a GET or POST request, or passed via a cookie.

From there I made a few php (simplified here):

// PAGE1.PHP
session_start();
$_SESSION['test'] = true;
echo "sid=" . session_id();

// PAGE2.PHP
session_start();
if ($_SESSION['test'])
    $echo "success";
else
    $echo "fail";

So, from my applet, I make a request to PAGE1.PHP and return me the session identifier. When I make a new request on page 2, I pass the session identifier as a parameter, and it seems that the session was not saved. I use

URL url = new URL("my/url/PAGE2.php?sid=" + session_id); 
URLConnection conn = url.openConnection();
conn.setDoOutput(true); 
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 

wr.write(data); // data is the post data created previously
wr.flush(); 

// Get the response 
BufferedReader rd = new BufferedReader(
    new InputStreamReader(conn.getInputStream())); 
String line;
while ((line = rd.readLine()) != null) { 
    System.out.println(line);
}

I tried using the POST and GET method and it does not seem to work.

So I wonder if this is possible, and if so, what will I miss?

thank.

+3
source share
2

PAGE2.php sid, _GET, .

page2.php :

session_id($_GET['sid']);
session_start(); 

:

session_start();
+3

GET - , - . cookie PHPSESSION - :

java- - ( java 1.4).

public String getCookie() {
  /*
  ** get all cookies for a document
  */
  try {
    JSObject myBrowser = (JSObject) JSObject.getWindow(this);
    JSObject myDocument =  (JSObject) myBrowser.getMember("document");
    String myCookie = (String)myDocument.getMember("cookie");
    if (myCookie.length() > 0) 
       return myCookie;
    }
  catch (Exception e){
    e.printStackTrace();
    }
  return "?";
  }

 public String getCookie(String name) {
   /*
   ** get a specific cookie by its name, parse the cookie.
   **    not used in this Applet but can be useful
   */
   String myCookie = getCookie();
   String search = name + "=";
   if (myCookie.length() > 0) {
      int offset = myCookie.indexOf(search);
      if (offset != -1) {
         offset += search.length();
         int end = myCookie.indexOf(";", offset);
         if (end == -1) end = myCookie.length();
         return myCookie.substring(offset,end);
         }
      else 
        System.out.println("Did not find cookie: "+name);
      }
    return "";
    }

, :

  getCookie("PHPSESSION"); // replace this with the cookie name in your /etc/php.ini

.

 conn.setRequestProperty("Cookie", "PHPSESSION=value"); 

sun java cookie

+4

Source: https://habr.com/ru/post/1752170/


All Articles