PostURL Tutorial


What is POSTURL?

PostURL is a feature used in our software that enables an application to retrieve the list of files that were uploaded to the FTP server. If we used the GET method to append the files to the URL, we would be limited to a length of 2000 characters on some browsers, thus if several files are uploaded, the URL can be truncated. But if we use POST, the limit is around 2 Megs which is large enough. Hence why POST is used.

Generally when a user logs into a web application, he/she get a sessionID which is stored either in a cookie or if cookies are disabled we can append them to the URL. Now after the user logs in he/she will be at their home page and may want to upload files to the FTP server using an applet.

Java Applets don't have access to the session cookie stored by the browser. Therefore a new session is created by the server everytime the applet does an HTTP POST. Because sharing of information between sessions is usually not permitted, the following workarounds can be used:

1. Using a server side script to write the contents of the HTTP POST into a file then retrieving the contents of that file by the server side script contained in "callurlaftertransfer" :- In this method, server side script in "posturl" will read the parameters passed by the applet in HTTP POST and write this information to a file. Then another server side script in "callurlaftertransfer" reads the data from the saved file.


For example:
Let's assume that we set the following parameters:

var posturl = "postProcess.php";
var callurlaftertransfer = "succeed.php";

The applet will do a HTTP POST to postProcess.php with the following parameters "f", the file list. "baseDir" as the base local directory and "totalSize" is the total size of all the files uploaded.
postProcess.php is configured to retrieve all the parameters and store their contents in some arbitrary file (for example, succeeded.txt)
Please note: You must have the value of the delimiter variable in the Javascript file the same as the one in the server side script.

After the files are uploaded and HTTP POST to posturl is called the applet will redirect the browser to callurlaftertransfer.
succeed.php is configured to open succeed.txt and retrieve the data submitted by the applet via HTTP POST to postProcess.php. At this point the programmer will have full access to user's session and can do whatever is required by the web application. Finally succeed.txt can be discarded once the data from HTTP POST has been parsed.

2. Appending the session ID to posturl - The syntax of how to append session ID to posturl varies with every technology. In general the posturl will look as follows:
var posturl="postProcess.php?session=<SESSION-ID>" This option is a lot cleaner because there is no need to create a temporary file, however Not all server side technologies are capable of parsing the session ID from the URL. This document outlines the syntax of how to pass session ID in most popular server-side technologies. Revert to option 1 if you are unable to get this option to work properly with your web application.

Below are Scripts written in the most common languages that can be used as a PostURL parameter, and the alternative way of attaching the information to a session object.

Important: It is necessary to make sure that the delimiter in the .js file matches the delimiter in the server side script.

Post URL in PHP

/* CODE TO PARSE AN HTTP POST REQUEST AND STORE THE DETAILS IN A FILE */

<?php

/* Script to Output File Names Received By Applet Author: Unlimi-Tech Software, Inc. */

/* Script Configuration Update these variables if you have modified them in the applet configuration. Variables are defaulted to applet default configuration. */

$filePostVariable = 'f'; //The POST variable containing the file listing with full paths

$fileDelimiter = ';'; //The delimiter that seperates the file list

$fileOutput = 'succeeded.txt'; //The file location to write the file list

/* Script Start */

//Get the file POST data

$filePost = $_POST[$filePostVariable];

//Break the file list into an array

$filePost = explode($fileDelimiter, $filePost);

//Initialize the output variable

$outputData = '';

if (is_array($filePost))

{

//Loop through the file list

foreach ($filePost as $tmp)

{

//Reverse the string for tokenizing purposes

$tmp = strrev($tmp);

//Tokenize the string

$fileName = strtok($tmp, "\\/");

if ($fileName)

{

//If a filename exists, reverse it back to original state

$fileName = strrev($fileName);

//Append the filename to the output variable

$outputData .= $fileName . "\r\n";

}

}

}

//Create and/or open the file with write permissions

$handle= fopen($fileOutput,'w');

//Flush the output to the file

fputs($handle, trim($outputData));

//Close the file

fclose($handle);

/* End Script */

?>

<html>
<!--The applet ignores the response from the server. There is no need to redirect or output
anything besides the empty HTML tag-->
</html>

The above is one way of getting the file list. Another way in PHP would be to rewrite the URL. This can be done by hardcoding the session id to the posturl link by adding ?<session-name>=<session-id> at the end of the link. Example, var posturl = "http://www.something.com/home.php?<session-name>=<session-id>.

Now the file list wil be stored in your session id object.

Back to Top

PostURL using JSP

If using JSP. You can do the same as above but with the script below. Save the script in a .jsp file and specify that file name in the posturl variable.

/* CODE TO PARSE AN HTTP POST REQUEST AND STORE THE DETAILS IN A FILE */

<%@ page language="java" import= "java.io.*,java.lang.*,java.util.*"%>
<%

String fileOutput = "succeeded.txt"; //The file location to write the file list
String test = request.getParameter("f"); //getting the file list from POST
%>
<%
try {
File cf = new File(".");
String sep = System.getProperty("file.separator");

String absPath = cf.getAbsolutePath();
absPath = absPath.substring(0, absPath.lastIndexOf('.'));
String currPath= absPath+fileOutput; //getting the location to store the file
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(currPath)));
StringTokenizer parser = new StringTokenizer(test, ";"); //tokenizing the string using the delimiter
Vector a= new Vector();
String output = "";
while (parser.hasMoreTokens()) //parsing through the tokens and adding them to the vector
{
a.add(parser.nextToken());
}
for(int y=0;y<a.size();y++) //iterating through the tokens
{
StringBuffer tmp = new StringBuffer((String)a.elementAt(y));
tmp=tmp.reverse(); //reversing the string so that the file name is at the begining
String temp = tmp.toString();
StringTokenizer st = new StringTokenizer(temp, "\\/");
String fileName = st.nextToken(); //getting the first token which is now the name of the file.
if(fileName.length()!=0)
{
StringBuffer sb = new StringBuffer(fileName);
sb=sb.reverse(); //reversing the file back to its original state
fileName=sb.toString();
output += fileName + "\r\n";
}
}
bw.write(output); //writing to the file
bw.close(); //closing the file
} catch (IOException e) {
}
%>

If you prefer to use the second method, ( rewriting the URL using sessions), it can be done by hard coding the sessionID to the posturl link by adding ;jsessionid=session at the end of the link. This will force the applet to use that sessionID to communicate with the web server and thus save all the details in the same session object.

Back to Top

Post URL in ColdFusion

If you are using ColdFusion, the procedure is basically the same, save the file under what ever filename with a cfm extension and specify that file name as the PostURL parameter.

<cfscript>
/**

* This is just a method for splitting a string.
* Splits a string according to another string or multiple delimiters.
*
* @param str String to split. (Required)
* @param splitstr String to split on. Defaults to a comma. (Optional)
* @param treatsplitstrasstr If false, splitstr is treated as multiple delimiters, not one string. (Optional)
* @return Returns an array.
* @author Steven Van Gemert (svg2@placs.net)
* @version 3, February 12, 2005
*/
function split(str) {
var results = arrayNew(1);
var splitstr = ",";
var treatsplitstrasstr = false;
var special_char_list = "\,+,*,?,.,[,],^,$,(,),{,},|,-,/";
var esc_special_char_list = "\\,\+,\*,\?,\.,\[,\],\^,\$,\(,\),\{,\},\|,\-,\/";
var regex = ",";
var test = "";
var pos = 0;
var oldpos = 1;

if(ArrayLen(arguments) GTE 2){
splitstr = arguments[2]; //If a split string was passed, then use it.
}

regex = ReplaceList(splitstr, special_char_list, esc_special_char_list);

if(ArrayLen(arguments) GTE 3 and isboolean(arguments[3])){
treatsplitstrasstr = arguments[3]; //If a split string method was passed, then use it.
if(not treatsplitstrasstr){
pos = len(splitstr) - 1;
while(pos GTE 1){
splitstr = mid(splitstr,1,pos) & "_Separator_" & mid(splitstr,pos+1,len(splitstr) - (pos));
pos = pos - 1;
}
splitstr = ReplaceList(splitstr, special_char_list, esc_special_char_list);
splitstr = Replace(splitstr, "_Separator_", "|", "ALL");
regex = splitstr;
}
}
test = REFind(regex,str,1,1);
pos = test.pos[1];

if(not pos){
arrayAppend(results,str);
return results;
}

while(pos gt 0) {
arrayAppend(results,mid(str,oldpos,pos-oldpos));
oldpos = pos+test.len[1];
test = REFind(regex,str,oldpos,1);
pos = test.pos[1];
}
if(len(str) gte oldpos) arrayappend(results,right(str,len(str)-oldpos + 1));

if(len(str) lt oldpos) arrayappend(results,"");

return results;
}
</cfscript>
<cfset filePostVariable="f">
<cfset fileDelimiter = "##">
<cfset test="#f#"> <!--getting the post -->

<cfset myarray=split(test,";")>
<cfset newarray=ArrayNew(1)>
<cfset outputData="">
<cfloop from="1" to="#ArrayLen(myarray)#" index="i">
<cfset arrayAppend(newarray, reverse(#myarray[i]#))>
</cfloop>

<cfloop from="1" to="#ArrayLen(newarray)-1#" index="j">

<cfset temp=split(newarray[j],"\")> <!-- If your system uses / as the file separator change the delimiter to "/" -->
<cfset out=reverse(#temp[1]#)>
<cfset outputData = "#outputData#" & "#out#" & #chr(32)# >
</cfloop>
<cffile action="Write" file="#GetTempDirectory()#/succeed.txt" output="#outputData#">

Appending the Session ID to the URL

Cold Fusion has a special variable called #URLTOKEN# which is used to append the session id’s in the query string of a link. Using urltoken you can maintain the state when cookies are not present. This means you'll then have to append #SESSION.UrlToken# at the end of the posturl file.

Back to Top

Post URL in ASP with C#

The following code is written in C#. Save it under an any filename you wish with a .aspx extension. Then specify the filename as the posturl parameter in the .js file.

<%@ Page Language="C#" Debug="true" %>
<html>
<head>
<title>Post URL using ASP C#</title>
</head>
<body>
<% String info = Request.Form["f"];%>
<h3>this if f <%= info %> </h3>
<%
String output="";
string[] arInfo = new string[10];
string[] arTemp = new string[10];
// define which character is seperating fields in this case it is ;
char[] splitter = {';'};
arInfo = info.Split(splitter);
for(int x = 0; x < arInfo.Length; x++)
{
char[] splitter2 = {'\\'};
arTemp = arInfo[x].Split(splitter2);
output = output + arTemp[arTemp.Length-1] + " ";
}
System.IO.TextWriter tw = new System.IO.StreamWriter("C:\\succeed.txt");
tw.WriteLine(output);
tw.Close();
%>
</body>
</html>

If you prefer the method of appending the session ID to the URL, get the current session id and append it to the url, succeed.asp?session-id=Session.SessionID thus the information from the post will be stored in the session object.

Back to Top

Post URL in ASP with VB

The following code is written in VB. Save it under an any filename you wish with a .aspx extension. Then specify the filename as the posturl parameter in the .js file.

Here is the code...

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" Debug="true" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Post URL in VB</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%
Dim s As String
Dim t As String
s = Request.Form("f")
t = Replace(s,";"," ")
Dim output As String
Dim words() As String
Dim i As Integer
' Split the string at the space characters.
words = Split(t)
for i=0 to words.Length-1
output = output + words(i) & vbNewLine
next
Dim writer As System.IO.StreamWriter = System.IO.File.CreateText("c:\myfile.txt")
writer.WriteLine(output)
writer.Close()
%>
<%= output%>
</body>
</html>

Again, If you prefer the method of appending the session ID to the URL, get the current session id and append it to the url, succeed.asp?session-id=Session.SessionID thus the information from the post will be stored in the session object.

Hopefully this tutorial was helpful and if you have any questions, you can post it on our forum and we will get back to you ASAP, or email us at info@utechsoft.com

Back to Top