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

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.

Related

Getting a HeartBeat from a C# Application and Posting it To Website

I've got a Minecraft Software written in C# that I want to send a heartbeat to my site. I've got the way to send the beat already written.
if (Server.Uri == null) return;
string uri = "http://GemsCraft.comli.com/Heartbeat.php";
// create a request
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
// turn request string into a byte stream
byte[] postBytes = Encoding.ASCII.GetBytes(string.Format("ServerName={0}&Url={1}&Players={2}&MaxPlayers={3}&Uptime={4}",
Uri.EscapeDataString(ConfigKey.ServerName.GetString()),
Server.Uri,
Server.Players.Length,
ConfigKey.MaxPlayers.GetInt(),
DateTime.UtcNow.Subtract(Server.StartTime).TotalMinutes));
request.ContentType = "application/x-www-form-urlencoded";
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
request.ContentLength = postBytes.Length;
request.Timeout = 5000;
Stream requestStream = request.GetRequestStream();
// send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Flush();
requestStream.Close();
/* try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Logger.LogToConsole(new StreamReader(response.GetResponseStream()).ReadToEnd());
Logger.LogToConsole(response.StatusCode + "\n");
}
catch (Exception ex)
{
Logger.LogToConsole("" + ex);
}*/
}
Now, I want to be able to retrieve the heartbeat in PHP, upload it to the SQL database, and then display each user's server in a table that will be displayed on the webpage
How do I do this?
portforwardpodcast's answer isn't very well-suited for your purposes, here's a process for you to ponder
Server accesses the following page: heartbeat.php?port=25565&maxplayers=25&players=2&name=Cheese_Pizza_Palace
Your PHP script will then do the following...
Go through each value, making sure they're all the types you want them to be (integers/strings)
Connect to the database
Update the server in the database if it already exists, create it if it doesn't
Return some value so the server knows that it completed successfully.
And to display the servers
Fetch all 'active' servers
Loop through them and display each one.
Things you'll need to figure out:
How to determine uptime
How to determine "active" servers
How to update/create MySQL entries
How to (properly) connect to a database. I would suggest using PDO since you're using PHP. It's a bit difficult to learn, but it's much more secure than writing the queries directly.
How to loop through all the GET variables.
Good hunting!
I would create a simple php page accept a get variable. something like www.site.com/beat.php?lasttime=123456&serverid=1 where the number us the unix timestamp. Then you need to re-work your c# to do a simple get request on a website. Finally your php should insert into a mysql table with a column for id, timestamp, server_id etc.
First you need to pull the data from the request. The $_REQUEST variable in php is nice because it works for both GET and POST:
http://php.net/manual/en/reserved.variables.request.php
Start out by var_dump or echo the fields you want. Once you can get the needed data into variables you are done with the first part. For the next part you need to create a database and table in MySQL. The best tool for this is phpmyadmin. If you have a host like godaddy (or some others) you can get at this from the control panel. If not you may need to install upload the phpmyadmin files yourself. It's a pretty simple tool to use:
http://www.youtube.com/watch?v=xxQSFHADUIY
Once your database has the correct columns, you need to insert the data from your php file. This page should help:
http://www.w3schools.com/php/php_mysql_insert.asp

Pass data between GWT and PHP

I'm a newbie with GWT and PHP, and after reading some tutorials it's not clear for me how to efficiently exchange data between the GWT frontend and PHP backend. I successfully followed the Google tutorials where is suggested to use the RequestBuilder class to get data from PHP.
But when I need to save the work done in GWT, how to efficiently pass the data to PHP?
It's not clear for me how to use the RequestBuilder for this task.
The solution that I found for now is
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
builder.setHeader("Content-Type", "application/json");
try {
Request request = builder.sendRequest("{\"done\":false,\"description\":\"Some text\",\"priority\":0}", new RequestCallback() {...
and in PHP side
$arr = json_decode(file_get_contents("php://input"),true);
$done = (int)$arr['done'];
$description = $arr['description'];
$priority = $arr['priority'];
mysql_query("INSERT INTO Tasks (done, description, priority)
VALUES ($done, '$description', $priority)");
Is this the best approach? Have someone found a working example in the web? Every opinion is welcome...
I think, working with JSON when interacting with non-Java servers is fine. You can build the JSON strings on the client side in a safer way by using the JSON module:
In your .gwt.xml file add
<inherits name='com.google.gwt.json.JSON'/>
Then you can construct your example string like
final JSONObject jsonObject = new JSONObject();
jsonObject.put("done", JSONBoolean.getInstance(false));
jsonObject.put("description", new JSONString("Some text"));
jsonObject.put("priority", new JSONNumber(0));
final String jsonString = jsonObject.toString();

How to make returned from PHP Data fill MXML Flex mx:List (Using actionscript and PHP)

I am Using Flex 3 and apache with PHP 5.2.
I am searching for simple as possible way to fill my mx:List with data using POST URLRequest.
In Flex builder I am using the next code
public var variables_se:URLVariables = new URLVariables();
public var varSend_se:URLRequest = new URLRequest("DataProvider.php");
public var varLoader_se:URLLoader = new URLLoader;
public function starter():void
{
varSend_se.method = URLRequestMethod.POST;
varSend_se.data = variables_se;
varLoader_se.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader_se.addEventListener(Event.COMPLETE, completeHandler_se);
variables_se.CountOflistItemsIWant = 30;
varLoader_se.load(varSend_se);
}
public function completeHandler_se(event:Event):void
{
textFild.text += " " + String(event.target.data) + ";"; // any result will apear in some textFild
// How to make result appear as list lines, how to form PHP answer and AS3 code for it?
}
How to make result appear as list lines, how to form PHP answer and AS3 code for it (If for example I want to return random numbers from PHP in desired in CountOflistItemsIWant cuatety)?
Maybe you could make your php script echo json encoded array like so:
<?php
echo json_encode(array('first', 'second', 'foo', 'bar'));
and in flex get it, decode it and use it as argument for array data provider for your mx:List
You can find information about communicating between php and flex with use of json here: http://www.adobe.com/devnet/flex/articles/flex_php_json.html
IMHO this is a larger architectural question. Here are the options:
Create a RESTful web service and have it output data in some text format (XML or JSON). You can use the HttpService objects in Flex to make request to your PHP restful web service and set result and fault handlers accordingly. Here's the quick start: http://www.adobe.com/devnet/flex/quickstart/httpservice/
If you need to remote objects directly between Flex and PHP, AMFPHP can be used: http://www.amfphp.org/
You can create a SOAP web service in PHP, some references...
http://developer.apple.com/internet/webservices/soapphp.html
http://php.net/manual/en/book.soap.php
... and use the Flex WebService object to make calls:
http://livedocs.adobe.com/flex/3/html/data_access_3.html

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.

AS3 and mySQL or XML: Saving user votes on server from a flash movie

A project of mine involves a flash movie (.swf) in a webpage, where the user has to pick from a number of items, and has the option to thumbs up or thumbs down (vote on) each item.
So far I have gotten this to work during each run of the application, as it is currently loading the data from an XML file - and the data is still static at the moment.
I need to persist these votes on the server using a database (mySQL), such that when the page is reloaded, the votes aren&apos;t forgotten.
Has anyone done this sort of thing before?
The two mains methods that I have found on the &apos;net are
either direct communication between AS3 and the SQL using some sort of framework, or
passing the SQL query to a PHP file, which then executes the SQL query and returns the SQL to AS3.
Which of these methods is the better option?
For the latter method (involving PHP), I have been able to find resources on how to acheive this when attempting to retrieve information from the database (i.e. a read operation), but not when attempting to send information to the database (i.e. a write operation, which is needed when the users vote). How is this done?
Thank you!
Edit: Implemented solution
Somewhere in the PHP file:
if ($action == "vote")
{
$id = $_POST['id'];
$upvotes = $_POST['upvotes'];
$query = "UPDATE `thetable` SET `upvotes` = '$upvotes' WHERE `thetable`.`id` = '$id' LIMIT 1 ;";
$result = mysql_query($query);
}
Somewhere in the ActionsScript:
public function writeToDb(action:String)
{
var loader:URLLoader = new URLLoader();
var postVars:URLVariables = new URLVariables();
var postReq:URLRequest = new URLRequest();
postVars.action = action;
postVars.id = id;
postVars.upvotes = upvotes;
postReq.url = <NAME_OF_PHP_FILE>;
postReq.method = URLRequestMethod.POST;
postReq.data = postVars;
loader.load(postReq);
loader.addEventListener(Event.COMPLETE, onWriteToDbComplete);
}
I am not aware of any framework that supports method-1.
I would use method-2 - but instead of making the query within Flash and passing it to PHP, I would rather pass the related data and construct the query in PHP itself. This is safer because it is less susceptible to SQL injection attacks.
This answer has an example of sending data from flash to the server - it talks about ASP, but the method is same for PHP (or any technology) - just change the URL.
Within the php code, you can read the sent data from the post $_POST (or $_GET) variable.
$something = $_POST["something"]
Many different options:
AMFPHP - binary messaging format between PHP and Actionscript/Flash.
LoadVars - for POSTing and GETing values to a PHP script.
JSON - Using the AS3Corelib you can post JSON formatted data to your web site (just like an AJAX script does).

Categories