2010-06-28 64 views
3

我目前正在尝试从一个小程序使用PHP网页的当前会话。我认为这很简单,但它并不像我那么坚强。从php man使用会话与PHP和Java

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. 

从那里我做了一些PHP(这里简化):

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

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

所以,从我的小程序,我做的请求page1.php中返回我的会话ID 。当我在页面2上做一个新的请求时,我将会话ID作为参数传递,似乎会话没有保留。我用

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); 
} 

我已经尝试通过POST和GET方法,它似乎并没有工作。

所以我想知道如果这是可能的,如果是的话,我错过了什么?

谢谢。

回答

3

您的PAGE2.php实际上并未使用您通过_GET传递的sid参数来启动会话。

则page2.php中,尝试:

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

代替普通老式:

session_start(); 
+1

我一直想它没有成功。再次阅读手册页后,似乎session_start是无效的。所以这是行不通的。 – Sauleil 2010-06-29 00:10:54

+1

你实际上在寻找'session_id($ _ GET ['sid']); session_start();' – 2010-06-29 00:13:56

+0

谢谢弗兰克!我误读了关于session_id的文档。我很努力,它总是在创建一个新的会话时调用它。现在它就像一个魅力! – Sauleil 2010-06-29 00:20:14

4

接受会话ID作为GET的一部分是坏的形式,和糟糕的主意安全明智的。我建议你从PHPSESSION cookie中检索会话ID,如下所示:

以下java代码片段是无耻的copied from here - 看看那个(虽然它是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 ""; 
    } 

其他地方在代码中使用抓取会话ID:

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

,并设置它在你的小程序。

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

远东更多的最新信息可在

+0

这可能是一个愚蠢的问题,但通过GET/POST和cookie传递会话ID之间的安全性有什么区别? (另外,我使用post后在php和java之间加密数据) – Sauleil 2010-06-29 12:54:17