How to access ASP classic session variable from PHP? - 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.

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
}

My solution was to auto-submit a webform which works both ways regardless of whether PHP to ASP or ASP to PHP.
On the leading page simply add an OnLoad to the body tag like so:
<body onload="document.xxx.submit()">
Where "xxx" is the is the ID of your form that contains the hidden fields that you want to pass. For example:
<form id="xxx" action="example.asp" method="post">
This will work locally and across domains.

Related

Database Post to another Database

I'm currently a front end developer for a website which lets users sign up and then make purchasing of items.For transactions, I'm using an API which the payment gateway company provided but when passing data via AJAX certain sensitive data are exposed for the users to see. I was wondering if there is a way that I can pass my parameters to a database (which I'm going to create), and then let the database do the AJAX posting so sensitive parameters can be hidden from the users. Also the database will store the response from the callback.
The ajax doesn't have to post to a database unless you want it to, but even then the database would not be what posts the data to a remote api. It's up to your backend php to do that.
Using jquery for the ajax call you would use something like:
$.getJSON("your_backend.php", function(result){
//whatever you want to do with the json returned from the remote site.
}
In your_backend.php:
<?php
$user = "user name";
$key = "key"
$headers = array(
'http'=>(
'method'=>'GET',
'header'=>'Content: type=application/json \r\n'.
'user:$user \r\n'.
'key:$key'
)
)
$context = stream_context_create($headers)
$url_returns = file_get_contents($api_url, false, $context);
echo $url_returns
?>
I haven't debugged this, so it won't work until you go through it, but it should give you an idea about how to proceed. Depending on how complex the connection is with the remote api you may need to use the cURL library for php instead of the file_get_contents.
If you want to save the information in your database you would write an insert statement from the backend php.

Custom session variables in Drupal 7

I'm trying to make a custom form in Drupal. This form call a web service and will receive some Json. in this Json response, I have three information (or an error) :
1. User name
2. User language
3. User custom Token (special for another webapp)
Those three info must be placed in session (or anything else) and will be shown in some webpages.
In example, on every page, It will be written "Hello Mr John", and on some web pages I want to show a icon + link with the custom Token to access to another web application, ...
We already have a lots of users, and we don't want to have all the users in the drupal DB.
How can I Do? I'm using Drupal 7
Thanks in advance
I wrote this function to deal with session in Drupal
function _mySite_session($key, $value = NULL)
{
static $storage;
if ($value)
{
$storage[$key] = $value ;
$_SESSION['mykey'][$key] = $value ; // I use 'mykey' as a session key because in case some other module uses 'type' in $_SESSION. So try to make it unique.
}
elseif (empty($storage[$key]) && isset($_SESSION['mykey'][$key]))
{
$storage[$key] = $_SESSION['mykey'][$key];
}
return $storage[$key];
}
To set a session variable:
_mySite_session("USERNAME", "Mr. John");
And to retrieve the value of the session variable:
$username = _mySite_session("USERNAME");

Convert PHP session (+ referral data) script to ASP.NET

This is a PHP script I use to get the referring website for each new visitor to my site.
If the visitor came from Google, I get the keyword they used to find the site.
This data is stored in the session then included along with the data from the contact form when an enquiry is sent. This allows clients with little knowledge of analytics to track converting keywords.
I need to convert this PHP to work on a site that uses .aspx pages. After researching asp.net for several hours, I feel like I still don't have a clue where to start!
<code>
<?php
session_start(); // start up your PHP session!
if (empty($_SESSION['google'])) {
// if session is empty, take the referer
$thereferer = strtolower($_SERVER['HTTP_REFERER']);
// see if it comes from google
if (strpos($thereferer,"google")) {
// delete all before q=
$a = substr($thereferer, strpos($thereferer,"q="));
// delete q=
$a = substr($a,2);
// delete all FROM the next & onwards
if (strpos($a,"&")) {
$a = substr($a, 0,strpos($a,"&"));
}
// we have the key phrase
$_SESSION['google'] = urldecode($a);
$_SESSION['referer'] = 'Google';
}
}
if (empty($_SESSION['referer'])) {
$_SESSION['referer'] = $_SERVER['HTTP_REFERER'];
}
?>
</code>
I'd really appreciate a point in the right direction with this.
Thanks.
You need to read up on the HttpRequest and HttpResponse classes. More specifically, the Request.ServerVariables collection, the Request.Cookies object, and the Response.Cookies object.

login to php website using RCurl

I would like to access with R to the content of a php website
http://centralgreen.com.sg/login.php?login=9-1501&password=mypassword
I have passed an example of login + password in the url, but I don't know how to press the login button through the url.
I would like to use the R package RCurl if possible.
The form submits by post - you are using a get request at the moment by the looks of things, you need to use post.
My guess is that rcurl is based on curl - and I know curl can do this, so should be possible.
recently I've been having the same problem. In my case I solved it like this, using RCurl package (with a POST request).
In this code two requests are done one after the other. The fist one, is in order to gain a session cookie (start session in the server). The application I was calling expected the session to be started by the time it checked the login credentials (this won't happen if you send the form upfront). Otherwise some warning about not having cookie support was raised. This might be the case of the asker (though it was time ago)... or someone else's.
login <- function (xxxx_user, xxxx_pass) {
url_login <- 'http://centralgreen.com.sg/login.php'
curlhand <- getCurlHandle()
curlSetOpt(
.opts = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")),
cookiefile = "cookies.txt",
useragent = 'YOUR R-PACKAGE NAME',
followlocation = TRUE,
# might need this in case the server checks for the referer..
httpheader = "Referer: http://centralgreen.com.sg",
curl = curlhand)
# (1) first call to initializate session. you get the session cookie
getURL(url_login, curl = curlhand)
params<- list( login = xxxx_user, password = xxxx_pass )
# might need to add some other hidden form param in case there are..
# (2) second call, sends the form, along with a session cookie
html = postForm(url_login,
.params = params,
curl = curlhand,
style="POST")
# ... perform some grep logic with 'html' to find out weather you are connected
}
# you call the function...
login("yourusername", "yourpass")
The 'perform some grep logic' note takes care of the fact that since you are targeting a system not designed for this kind of programatical log in, it's not going to give you any nice hint on the result of the attempt ... so you might need to parse the raw html string you receive against some key sentences (eg: 'wrong username or password' ...)
hope it helps

asp.net form submission problem

I need to accomplish the following and need help with #2 below
My site has a page with form and the submitted form data needs to be written to a database on my site.
After it is written to the database, the same data submitted on the form needs to be sent to a page that processes it on another site so as if the form submission came from a page on that other site. The page that processes it on the other site is a php page.
It's a bit unclear, but my guess is that you're trying to do a 'form post' to the other .php page after your data is written to the database.
You can more information from this wonderful Scott Hanselman article, but here is the summary:
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
The ideal solution to your problem is that you create a web service on the php site and your asp.net code calls the web service. http://en.wikipedia.org/wiki/Web_service
Creating a web service in PHP: http://www.xml.com/pub/a/ws/2004/03/24/phpws.html
Calling a web service in ASP.Net: http://www.codeproject.com/KB/webservices/WebServiceConsumer.aspx
Alternatively you could create a http request from your asp.net to the php site posting all the form elements to the php site.
Here is an example: http://www.netomatix.com/httppostdata.aspx
NB: You are almost guaranteed to run into problems with the second approach in the medium to long term, I don't recommend it unless you don't have control over the php site.

Categories