google app engine problem of post method in flash and php - php

I'm trying to deploy flash files embeded in html to the google app engine.
Flash(action script 2.0) uses "post" method to send hostname and get its ip address through php function gethostbyname().
In fact, I know google app engine does not support php.
So I tried to use another way to deploy ipPHP.php in other free web server and only flash file in google app engine.
But it does not work and I can not know why.
Can you give me a tip for this problem ?
--------------domaintoip.fla ---------------------
result_lv = new LoadVars();
result_lv.byname = _root.domainnm;
trace("Sending... " + result_lv.byname);
result_lv.onLoad = function (success)
{
if (success)
{
_root.ip = unescape(this.result);
trace("Return value from the PHP : " + unescape(this));
if(_root.ip.length==5){
_root.flag=1;
}
else{
var mystring=_root.ip;
arr=mystring.split(".");
_root.ipby1=arr[0];
_root.ipby2=arr[1];
_root.ipby3=arr[2];
if(arr[3].length==15)
{
_root.ipby4=arr[3].substr(0,3);
}
if(arr[3].length==14)
{
_root.ipby4=arr[3].substr(0,2);
}
if(arr[3].length==13)
{
_root.ipby4=arr[3].substr(0,1);
}
_root.flag=0;
}
}
else
{
trace("Cannot call the PHP file...");
_root.flag=1;
}
}
result_lv.sendAndLoad("http://anotherserver../ipPHP.php", result_lv, "POST");
-------------- ipPHP.php ---------------------
<?php
$Var1 = $_POST['byname'];
$rtnValue = gethostbyname(trim($Var1));
if(ip2long($rtnValue) == -1 || $rtnValue == $Var1 ) {
$rtnValue =0;
echo (result=$rtnValue");
}
else {
echo("result=$rtnValue");
}
?>

If your site is hosted on the app engine, you cannot make AJAX calls to a host other than the app engine due to the Same Origin Policy. This limitation is generally true, and is not specific to the app engine. To generalize, for any web page hosted at domain X, that web page cannot make AJAX requests to domain Y.
You actually are experiencing a much more fundamental problem: When the only tool you have is a hammer, every problem looks like a nail. In fact, you can trivially handle POST requests with the app engine using the doPost method, and you can very easily get the client's IP address in a very similar manner as your PHP script. There is absolutely no reason to use PHP here; you've set up a completely new server to call one built-in PHP function? That's insane; you can do the exact same thing with an app engine servlet.
Consider the following code:
public void doPost(HttpServletRequest request,HttpServletResponse response) {
/* get "byname" param, equivalent to $POST['byname'] */
String rtnValue = request.getParameter("byname");
/* TODO: your if statements and other logic */
/* print response to client, equivalent to your echo statement */
response.getWriter().print("result=" + rtnValue);
}

Related

Send and read serial data from a PHP Desktop app using Node.js or PHP

As written in the title I made a stand alone web app using PHP Desktop, and now i want it to send and read data from a serial port.
I tried first to use this PHP Serial class (https://github.com/rubberneck/php-serial), but i had some problems, particularly on reading data, so i moved to javascript and node.js.
I installed Node.js and, using npm, serialport and ws packages, and I made the serialport work only with the node command on Windows cmd. I tried to follow some examples and extend the code to my PHP Desktop App using also the ws package but nothing seems to work and now I don't know how to go on.
Do you guys have any kind of suggestion? (Particularly on how to go on with the ws package)
What's the best solution to do this?
Thanks in advance.
Here's the code that I used:
PHP code:
<?php
session_start();
include_once 'PhpSerial.php';
if(isset($_POST['serial'])) {
$serial = new phpSerial;
$serial->deviceSet("COM3");
$serial->deviceOpen('w+') ;
$serial->confBaudRate(115200);
$serial->sendMessage($_POST['serial'],1);
$_SESSION['serial_data'] = $serial->readPort();
$serial->deviceClose();
}
else
header('Location: index.php');
?>
JS code: (without the ws part, that didn't want to work)
var serialport = require('serialport');
var portName = "COM3";
var myPort = new serialport(portName, {
baudRate: 115200
});
myPort.on('open', showPortOpen);
myPort.on('data', readSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);
function showPortOpen() {
console.log('port open. Data rate: ' + myPort.baudRate);
}
function readSerialData(data) {
console.log(data);
}
function showPortClose() {
console.log('port closed.');
}
function showError(error) {
console.log('Serial port error: ' + error);
}

Can I run asp.net code on a PHP server?

I have a domain using Php but I added asp.net code. And try to execute that it displayed asp.net code only. Whether it is possible to add asp.net code under php domain by using any plugin or some third party help. If yes means, give some idea.
You could use HttpWebRequest to get a result off a PHP page which might help you a bit. An example taken from: https://stackoverflow.com/a/9818700/4068558
string myRequest = "abc=1&pqr=2&lmn=3";
string myResponse="";
string myUrl = "Where you want to post data";
System.IO.StreamWriter myWriter = null;// it will open a http connection with provided url
System.Net.HttpWebRequest objRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(myUrl);//send data using objxmlhttp object
objRequest.Method = "GET";
objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(myRequest);//send data
myWriter.Close();//closed the myWriter object
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
myResponse= sr.ReadToEnd();
}
Otherwise, the problem is IIS will see a .php file and compile it with PHP. Vice versa with ASP. Although a work around for running PHP inside ASP.NET is phalanger.

Google API request every 30 seconds

I'm using Live Reporting Google APIs to retrieve active users and display the data inside a mobile application. On my application I'd like to make a HTTP request to a PHP script on my server which is supposed to return the result.
However I read on Google docs that it's better not to request data using APIs more often than 30 seconds.
I prefer not to use a heavy way such as a cron job that stores the value inside my database. So I'd like to know if there's a way to cache the content of my PHP scrpit na dmake it perform an API request only when the cache expires.
Is there any similar method to do that?
Another way could be implementing a very simple cache by yourself.
$googleApiRequestUrlWithParameter; //This is the full url of you request
$googleApiResponse = NULL; //This is the response by the API
//checking if the response is present in our cache
$cacheResponse = $datacache[$googleApiRequestUrlWithParameter];
if(isset($cacheResponse)) {
//check $cacheResponse[0] for find out the age of the cached data (30s or whatever you like
if(mktime() - $cacheResponse[0] < 30) {
//if the timing is good
$googleApiResponse = $cacheResponse[1];
} else {
//otherwise remove it from your "cache"
unset($datacache[$googleApiRequestUrlWithParameter]);
}
}
//if you do no have the response
if(!isset($googleApiResponse)) {
//make the call to google api and put the response in $googleApiResponse then
$datacache[] = array($googleApiRequestUrlWithParameter => array(mktime(), $googleApiResponse)
}
If you data are related to the user session, you could store $datacahe into $_SESSION
http://www.php.net/manual/it/reserved.variables.session.php
ortherwise define $datacache = array(); as a global variable.
There is a lot of way of caching things in PHP, the simple/historic way to manage cache in PHP is with APC http://www.php.net/manual/book.apc.php
Maybe I do not understard correctly your question.

Silverlight Localhost on Xampp

I am trying to retrive data to my SL application from PHP, MySQL service which is hosted locally on Xampp.
I can see my php file running OK and deliver results via JSON (http://localhost/silverlight/data.php) but SL cannot receive it. I belive it has something to do with correct URl path but I cant figure it out. Also I've putted clientaccesspolicy.xml file to allow cross-domain access but with no avail:(
public partial class MainPage : UserControl
{
WebClient wc = new WebClient();
ObservableCollection<ToDoItem> myToDoList = new ObservableCollection<ToDoItem>();
string baseURI = "http://localhost/silverlight/";
public MainPage()
{
InitializeComponent();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri(baseURI + "data.php",UriKind.Absolute));
}
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null && e.Result!= "")
{ JsonValue completeResult = JsonPrimitive.Parse(e.Result);
string resultType = completeResult["returnType"].ToString().Replace("'", "").Trim();}
The clientaccesspolicy.xml file you use only allows cross-domain access for web service requests (as specified by http-request-headers="SOAPAction")
For WebClient to work the way you use it, you need to enable content requests as well.
Try specifying http-request-headers="*" or http-request-headers="SOAPAction,Content-Type".
Also, do check that the clientaccesspolicy.xml file is located at the root of the host, i.e. http://localhost/clientaccesspolicy.xml. Eventually when you decide to deploy your application, you'll have to make sure the file is placed in the root of the deployment host as well, e.g. http://example.org/clientaccesspolicy.xml

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