asp.net form submission problem - php

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.

Related

How to run php function after redirecting user to another page?

I am building a form which the user fills and then I save it into the db. Then I retrieve users who match the criteria and for each one of them I store into another table and also send them an email.
$userModel = new User();
$currentUser = $userModel->findUserById($user->id);
$requestModel = new Requests();
$success = $requestModel->saveRequest($currentUser->usr_id, $tagId, $title, $task, $fixed, $price, $hour, $quality, $multiple, $datetime, $postal, $cityId, $travel);
if($success){
$request = $requestModel->getUserLatestRequest($currentUser->usr_id);
if($request){
$user = new User();
$alluserids= $user->getAllSkillCityUserIds($cityId, $tagId);
$targetId = (array_column($alluserids, 'usr_id'));
//error_log("<pre>targetId".print_r($targetId,true)."</pre>");
foreach($targetId as $target) {
if($target == $currentUser->usr_id){
continue;
}
$lead = new RequestsLead();
$lead->addRequest($request->req_id, $request->req_userid, $target);
$contractor = $userModel->findUserbyId($target);
$nemail = new NotificationsEmail();
$nemail->sendGotRequest($contractor->usr_email, $contractor->usr_firstname);
}
}
$this->flash->success('<div data-toggle="notify" data-onload data-message="Thanks for using our service!." data-options="{"status":"success"}" class="hidden-xs"></div>');
$this->response->redirect($this->url->get(""));
}else{
$this->flash->error('<div data-toggle="notify" data-onload data-message="Sorry! Please try again." data-options="{"status":"danger"}" class="hidden-xs"></div>');
$this->response->redirect($this->url->get("request"));
}
The problem comes when there are alot of users and this function will need to finish running before the user is redirected back to the page with the flash message. How can I modify this so I redirect the user back to the page with the flash message first then run the php foreach functions storing into the db and sending emails after?
I tried switching the order of the functions but once the user is redirected with flash message the php functions stopped proceeding.
PHP is a server side scripting language. It's essentially (but not completely) stateless.
What this means is that when a PHP Page is loaded, it executes it's required PHP code on the server, and then sends the response to the browser. There is no way to re-xecute PHP code after the page has been sent to the client without a new call to the server.
In your case, you're redirceting clients to a new PHP page. That's great, but the new PHP page is a new script being run on the server, it has no concept of what the previous page was doing.
In order to execute the PHP Code AFTER the page has loaded, you will need to use AJAX to send out a request to the PHP Server to execute this request in the background if you want to do it without redirecting the user again, or redirect the user again after displaying the 'flash' message.
Note that with AJAX you can also use the original page - without any redirection - to execute this request AND to display the flash message (at the same time!).
For more information about sharing data between pages:
How do I pass data between pages in PHP?
Passing POST data from one web page to another with PHP
Transfer variables between PHP pages
For more information about AJAX requests and PHP:
Making Ajax service calls with PHP, jQuery, and JSON
(Non-Stackoverflow Link)
Beginner’s Guide to Ajax Development with
PHP (Non-Stackoverflow Link)
What you mention would require some way for the script to keep running beyond the response being sent back to the user. PHP does not work this way - you can start writing content to the output buffer, but the browser will still wait until the entire response has been returned.
Instead, you should think of some process to temporarily store the information you need, and process these asynchronously. e.g. store them to a database and run a cron script or deamon to do this.

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.

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

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

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