PHP Function calls java and gets an answer :)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GroovyinAz
Forum Newbie
Posts: 8
Joined: Tue Oct 01, 2002 6:26 pm
Location: Tucson,AZ

PHP Function calls java and gets an answer :)

Post by GroovyinAz »

Code: Select all

<?php
/**
 * function callJava()
 * 
 * @param $functionName 
 * @param $params
 * @return 
 * 
 * Author: Seth Webster 
 * Date	 : Mon, Oct 14, '02
 * Rev   : 1
 * 
 * This is a quick and dirty way to call a javascript function
 * and get it's return value in php.  Of course, there is no way
 * to pass the value without using forms, so the page must be reloaded.
 * 
 * However, this is useful for many applications.
 * 
 * I guess, you could pass the function as a string, rather than reading
 * it from the file, but I found this was the easiest.
 * 
 * APPLICATION:
 * 
 * 	In your PHP file, somewhere insert your script:
 * 
 *	 	<script>
 * 			function javaFunctionofsomesort(p1,p2,p3...) {
 * 				return stuffiwanted;
 * 			}
 * 		</script>
 * 
 *  Then, anywhere in your PHP:
 * 
 * 		if (! $javareturnval) callJava("javaFunctionofsomesort",array("p1","p2","p3"));
 *
 *  callJava will then generate a dummy form, call the function, store the return in 
 *  $javareturnval and "GET" the form to your PHP page.
 * 
 *  Obviously, once callJava has been called, you can access $javareturnval from 
 * 	anywhere in the global scope (providing register_globals is on, if not, refer 
 *  to the countless global variable parsing examples out there).
 *  
 **/
 
 
function callJava($functionName,$params) {
	
	global $PHP_SELF;  			// Global reference to self
	global $QUERY_STRING;		// to maintain original query string
		

	/* our dummy form */
	
	$formstr =	"<form name="javapass" action="$PHP_SELF?$QUERY_STRING" method="post">\n\r" .
				"<input name="javareturnval" type="hidden" value="">\n\r" .
				"</FORM>\n\r";

	echo $formstr;

	/* read contents of current file */
	
	$fp = fopen(".". $PHP_SELF,"r") or die("Failure");
	
	$contents = fread($fp,filesize("." . $PHP_SELF));
	
	fclose($fp);
	
	/* find the function $functionname */
	
	$header = stristr($contents,$functionName);
	
	$par = "";
	
	/* turn our array of params into comma delimited string */
	
	$parfinal = implode(",",$params);
	
	$functionName .= "(" . $parfinal . ");";  // creates functionname(p1,p2,p3...)
	
	/* 
	* The javascript code to update and automatically 
	* submit the form with the return value ($javareturnval)
	*/
	
	$scriptstr =	"<script>" .
					"document.formsї0].elementsї0].value= ". $functionName. "\n\r".
					"timerID=setTimeout("document.javapass.submit()",1);\n\r".
					"</script>\n\r";
	echo $scriptstr;
	
}
?>

?>
Let me know if you find this useful!
Post Reply