I have a program that will make a web request to a php page (there will not be a browser involved here), and I need to send some data using php back to the program... how do I do this?
Just use echo to echo the thing you want sent back.
<?php
echo "thing that i want to send back";
?>
Have you considered a webservice? It might be overkill. Otherwise.. a POST or GET and echoing the response with PHP..?
What you're describing is basically a website.
You should echo what you want to return, like the others said.
for c# application, you should wait for response, and read the response stream to get the echos.
public GetResponeFromPHP()
{
HttpWebRequest request = null;
HttpWebResponse resp = null;
try
{
request = (HttpWebRequest)WebRequest.Create("http://www.URL_of_php.php");
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
// execute the http request and get the response
resp = request.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
//read the response stream
String responseText;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
responseText = sr.ReadToEnd();
}
// Now use respones text to get the echos //
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (resp != null)
resp.Close();
}
}
post and get really seem like the solution here. Although I am not very comfortable with the technique because it is prone to errors if parameters in the URL are incorrect or not validated. Maybe consider something other than the PHP? but hey the answer is that it would work like the others said above :)
Depending on the type of data you need returned from PHP, and assuming you have control of both the C# application and the PHP application, you will most likely use something such as the WebClient class, which allows you to make an HTTP call to a URL, which you would point to your PHP application. Once the request is made, you do whatever processing is necessary in your PHP application, and then most likely echo it back to the C# application (also, depends on the type of data you're using)
A simple HTTP response consist of headers and body.
The headers are not displayed in your web browser, but take place in the client(browser) server communication (web server) - simply said.
The web server will return to your program also so named headers, for which you will have to take care about.
Using your php script you can sent your output with echo:
<?php
echo 'Responding to the program...';
?>
Related
I am looking for a way to get an echo (or anything else) between 2 functions, the first being called via Ajax.
Here is what I am doing :
I upload via Ajax a video to the server where it is temporary stored.
then pass the video to a private function that send it to youtube via the API and after, unset the video on the server.
My question : between the 2 functions, is there a way to get from the PHP script something that can be handled by the client to inform him of the progress ?
I tried :
to send JSon
to update a session checked by JS while the Ajax call
flush() and ob_flush()
but always, data is returned at this end of the 2nd function (when I don't need anything anymore), as if, while the call and all that is after, PHP was unable to say something
I 'd like :
function upload()
{
//uploading
if(ok)
{
//echoing something there (the main goal)
goYoutube();
}
}
private function goYoutube() {
//etc...
}
and what I have is :
function upload()
{
//uploading
if(ok)
{
goYoutube();
}
}
private function goYoutube()
{
//etc...
//echoing something there (the bad bad bad useless thing)
}
It is with CodeIgniter and I don't have the hand on the server.
I don't need code, just an idea (which will be greatly appreciated)
Of course, something like "don't lose your time guy, it can't be done" is ok !
Thanks.
PHP is a server side language and I don't think it'll output something until the script finished executing. If I were you I would try to split those functions in two separate AJAX request.
The first request gives the user the answer that everything is ok (or something like "please wait") and the second request makes the call to the YouTube API.
You could do this by establishing a websocket connection and sending events from the server to the client. I usually do this in nodejs using socket.io. I see there is a similar option for PHP: elephant.io
So the order of things would be:
Establish websockets connection with server (before sending video)
In the clientside, listen for the event you will receive and do whatever update there.
Do the video upload.
In the serverside, send a websockets event where you would place you "echo"
Take a look at it, I really think it will do.
I am trying to create a web service which takes a number of arrays (of type double) and returns the mean value of each of these arrays.
To get started I have written a PHP script which retrieves the array using the HTTP GET method and calculates its mean, returning it in the response in JSON format:
<?php
header("Content-Type:application/json");
if(!empty($_GET['array'])) {
//calculate mean of each array and send results
$array = $_GET['array'];
$mean = array_sum($array)/count($array);
respond(200,"OK",$mean);
} else {
//invalid request
respond(400,"Invalid Request",NULL);
}
function respond($status,$message,$data) {
header("HTTP/1.1 $status $message");
$response['status']=$status;
$response['message']=$message;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
However, I realized very quickly that with a large array (say, 15000 values) my query string used to pass the values will become so large as to be impractical, if it even works (I have read that many systems place a limit of ~2000 characters on the length of a URL). So, I am looking for a different way to pass the data to my service that will not be limited in this way. The arrays will be generated by a client program. I am using the latest XAMPP stack for the server.
You can use POST instead of GET for that. The way to do that deppends on the language of your client. For example, using jQuery:
$.post('http://yourserver.com', yourArray, function (data, status) {
//handle the response of the server
});
For the data you're talking about, you're right, GET is not the appropriate way to send it. Use POST.
I'm assuming you have control over the client program, in which case, change the client to use HTTP Request, with the request content in the body.
If you don't have control over the client program, you are out of luck. If the client sends the request in $_GET, you must receive it that way.
So i am trying to communicate between dart clientside and a php server side using AJAX. Since direct execution is not possible. I compiled the dart to javascript and then run it on a apache server.
json data is generated at client end, But there is no response from the the server
dart code
import 'dart:html';
import 'dart:json';
void main() {
query("#clicker").on.click.add(callServer);
}
void callServer(Event event) {
var data ={ 'name':"sendname"}
,jsondata=stringify(data);
print(jsondata);
var req = new HttpRequest();
req.open('post','http://localhost:8080/darttest/server.php',true);
//req.setRequestHeader('Content-type','application/json');
req.send(jsondata);
print(req.responseText);
}
php side i just echo the content received
<?php
$name = $_POST['name'];
echo $name;
?>
This is my first try at dart programming, so do let me know if this approach is even possible
Is localhost:8080 serving both the static Dart (as JS), and the php? If not, you're likely coming across the access-control-allow-origin issue (which is a browser security issue).
This prevents one site posting date to another site.
Work-arounds:
Ensure that the site serving php returns the correct CORS headers: http://enable-cors.org/server.html
Serve the static Dart/JS files from the same URL (localhost:8080)
For more information, read these:
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
CORS with Dart, how do I get it to work?
Creating a bot/crawler
Update Workaround 3 is described here (for Chrome / Dartium):
https://groups.google.com/a/dartlang.org/d/msg/misc/kg13xtD7aXA/uxeXXrw3CG8J
You can add the parameter "--disable-web-security" to chrome.exe to disable cross domain check.
(Of course, this is only useful while you are developing)
To read the response, you have to put your code in a callback on readyStateChange :
var req = new HttpRequest();
req.open('post','http://localhost:8080/darttest/server.php',true);
req.on.readyStateChange.add((e){
if (req.readyState == HttpRequest.DONE && req.status == 200){
print(req.responseText);
}
});
req.send(jsondata);
With your code the http request was not processed when you tried to read the response. You have to wait the completion of the request to read the response.
this is not sending data between dart and php. this is sending data from dart to php!!!
Here's the particular situation: I'm using a bookmarklet to call a .js that sends a POST request to a PHP file on my server. Here's the POST request in the .js file:
var snd = ("qu=" + encodeURIComponent(t) + "&dl=" + encodeURIComponent(dl) + "&dt=" + encodeURIComponent(dt));
xr = new XMLHttpRequest();
xr.open("POST", "http://quotebook.us/s/process2.php",true);
xr.onreadystatechange=function() {
if (xr.readyState==4) {
var xmldoc = xr.responseText;
window.alert(xr.responseText);
}
}
xr.send(snd);
And below is what I'm doing in PHP. But try as I might, I can't figure out how to get something BACK to the .js file so it can display it in an alert (and consequently, so I can confirm that it's sending the data in the first place).
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
echo "This page is not for viewing";
exit;
}
$qo = $_POST["qu"];
$dl = $_POST["dl"];
$dt = $_POST["dt"];
echo "First parm: $qo, second param: $dl, third param: $dt";
?>
Ultimately I want to take these variables and write them to a MySQL database, but I'm at least a day away from learning how to do that...
Any help on this process would be very welcome, I've had a heck of a time finding anything about processing POST requests that AREN'T sent by a user form. Apparently writing bookmarklets that send data to MySQL is a black art ;)
Use firebug for firefox.
To test that you're doing it correctly, I'd probably use Firebug on Firefox or Dev Tools on Chrome; with either, you can see the actual HTTP data sent or received. But I think your real question is, why isn't the POST working? (You might consider updating your question title.)
And the answer may be that you're not setting the content type. POST is generic, you can post anything. In your case, you're posting URL-encoded data, so try adding:
xr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
...after your open call. Some examples here and here.
I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.