Search code examples
phparchitectureasp-classic

How to access ASP classic session variable from PHP?


I have a login protected back office website written in ASP classic running on Windows. Login status is stored in a session variable. I also have a PHP page that should be accessible only to logged in users. How do I check in PHP that the client is logged in to this website?

P.S. There may be multiple users accessing the page at the same time.


Solution

  • By assuming both PHP and ASP applications share the same domain name, here's a step by step guide.

    1 - Create an asp file named sessionConnector.asp.

    2 - In sessionConnector.asp, serialize the Session.Contents object into a format that PHP can deserialize, JSON for example. You can use JSON.asp from aspjson.

    <%@Language=VBScript CodePage=65001%>
    <!--#include file="JSON.asp"-->
    <%
    Set JSONObject = jsObject()
    
    For Each Key In Session.Contents
        If Not IsObject(Session.Contents(Key)) Then 'skip the objects cannot be serialized
            JSONObject(Key) = Session.Contents(Key)
        End If
    Next
    
    JSONObject.Flush
    %>
    

    3 - Create a PHP function named GetASPSessionState().

    4 - In GetASPSessionState(), make an HTTP request for sessionConnector.asp by specifying the Cookie header filled with $_SERVER["HTTP_COOKIE"] which must contains identifier of the ASP Session, so ASP can identify the user and the response will vary by user.

    5 - After fetching the response (string of JSON), deserialize by using json_decode and look for the ASP session variable.

    function GetASPSessionState(){
        if(stripos($_SERVER["HTTP_COOKIE"], "ASPSESSIONID") === false){
            # since ASP sessions stored in memory 
            # don't make request to get ASP session state if the cookie does not contain ASPSESSIONID
            # otherwise IIS will create new redundant sessions for each of your checks so it wouldn't be a memory-friendly way
            # returning an empty array
            return array();
        } else {
            $options = array('http' => 
                array('method'=>"GET", 'header' => "Cookie: " . $_SERVER["HTTP_COOKIE"])
            );
            $cx = stream_context_create($options);
            $response = file_get_contents("http://mywebsite.com/sessionConnector.asp", false, $cx);
            return json_decode($response, JSON_FORCE_OBJECT);
        }
    }
    
    $aspSessionState = GetASPSessionState();
    if($aspSessionState["IsLoggedIn"] == true){
        //user previously logged in with the ASP
    }