How to send out a http reponse - php

I am a php newbie and I came across some problems when use php with apache.
I don't want to use browser to send or receive http request so that I have to manually deal with this problem. On server side, I can use file_get_content("php://input") to extract body from the http request, but how can I build the http response? The method is "post" and I want to insert a xml string to the response body. Thank you for help!

Example:
See: http://php.net/manual/en/function.header.php
For HTTP codes, Google them up.

Simply echo "whatever" will return that back to the users browser. Remember that PHP is an interpreted language originally for inline scripting (i.e. mixing with HTML) prior to sending to the browser. So a file:
<?php echo "here"; ?>
will just return that reply to the users browser when they go to the appropriate URL. Adding any parsing etc. can be done in addition to this basic application logic.

Related

How have safe HTTP Request Method

when use GET Method for receive JSON data , we can acsses the result directly from web browser , for example i send a mydata value from ajax to a main.php file and it process and get answer show a result some thing like below :
<?php
if (isset($_GET["mydata"])) {
if ($_GET["mydata"]=="hello"){
echo "hello world";
}
}
?>
but when a user call it in browser directly like http:mysite.com/mydata.php?mydata=hello recive answer . i want dont allow users to get answer of http request directly , and just can show it from ajax result of main page is it possible ?
You're asking how to prevent an ajax-only request from being accessed directly by copy-pasting the URL into the web browser; that is, only allowing the URL to be accessible via ajax on the main web page.
Well, there are a few things you can try:
Check the Referrer for the URL of the main page with $_SERVER['HTTP_REFERER']
Set a header in Javascript using xhr.setRequestHeader() and then ensure it's value by checking for $_SERVER['HTTP_X_....'] in PHP
Like Jay Bhatt recommended, check for the X_REQUESTED_WITH header, but be aware this might not always be set (see: X-Requested-With header not set in jquery ajaxForm plugin)
However, in any of these situations you should be aware that anyone who knows what they are doing can easily set any HTTP header, variable, or even modify the referrer which is sent to the server. As such, there is no 100% guarantee that your resouce can be accessed only via AJAX on the main web page. There is no control built in the internet to verify where a request is coming from, so anyone can easily spoof or fake it.

PHP How to respond to HTTP Request and continue processing?

I am working with an API for a payment gateway that does a callback request.
When the callback request is made, the gateway expects me to respond with "OK".
Nothing more or less. And that doesn't mean html rendered response. Just a callback file with those 2 letters. Note that doesn't mean it wants HTTP Status Code 200/OK... it wants actual data (not headers) for the word "OK".
So this won't work:
<html><body>OK</body></html>
This will work:
<?php echo "OK"; ?>
however, after I send back OK, I need to do some stuff on the server side and then redirect the browser page to another page. But when I try to do:
<?php
echo "OK";
header('Location: http://www.store.com/success.php');
exit;
?>
The gateway ignores the echo "OK" and instead reads the html off of the success.php page that I redirect to.
So how can I send back just the OK but continue doing things on my side?
Thanks
You can't send content then redirect. The redirect header setting must be done alone.
You could try using flush(); to force php to write out the OK.
Would it be acceptable to move the redirect into client side either with javascript or meta refresh tag?
Before you send the OK you could call PHP via commandline to make PHP acting like multi threated.

getting cookie from an external javascript in php before generating HTML output

Is it possible getting cookie from an external js with Php before generating HTML to the browser?
Something like
<?
//Get if i have some cookie information
if($_COOKIE["js_app"])
$cookie_js = $_COOKIE["js_app"];
//now, talk with some app.js
if($cookie_js)
$cookie = some_function(target = 'some_domanin/app.js',$cookie_js);
else
$cookie = some_function(target = 'some_domanin/app.js');
$_COOKIE["js_app"] = $cookie;
//now i can generate the HTML output.
....
?>
It isn't possible because the javascript would never be executed. Your some_function (assuming it used cURL to make the request and pass along the cookie), would just receive the javascript code (like what happens when you view javascript source in your browser).
When JS is loaded by the browser, the browser's javascript interpreter handles parsing and executing the javascript.
Edit: Hmm... googling for "php javascript interpreter" resulted in http://j4p5.sourceforge.net/index.php. Never used it before and probably never will but if you don't need to interact with the user-side of things, that might help you out.
You are looking for a way to send request with cookies, and get the cookies from the response using PHP, right? I think PEAR HTTP_Request is what you are looking for, although you have to install it on your server as a package.
If that is not an option, I guess you will have to do HTTP requests using sockets.
UPDATE: If you are setting the cookies using Javascript, you will have to parse the javascript - not really an option. These functions only work when the cookies are set server-side.

Jquery Post to external php

I want to post to an external php file and get the result. It a php that i have hosted in my server online. I want the static page in my localhost post by ajax and load the html in a div. But I'm not able to do this.
$.post("http://www.site.com/index.php", { font: "panchami", input: "hi" } );
Is there anything wrong in this?
The Same Origin Policy prevents Ajax calls to external domains.
Popular workarounds include
JSONP
Embedding the data in an iframe instead
Using a server-side proxy the does the fetching (see #BrunoLM's answer for a PHP example; it is possible in any server-side language)
YUI's Get as shown in #Alex's answer
depending on what your use case is.
Javascript doesn't allow cross domain requests.
What you can do is a PHP file on your server that reads the contents of the other site:
<?php echo file_get_contents($_REQUEST['url']); ?>
Then make requests to your file, like so:
$.post("proxy.php?url=external_url", ...);
Or using GET, for example:
http://developer.yahoo.com/yui/get/
This kind of request is dangerous, it is called a Cross-Site request and is forbidden by most browsers. If you look in your error console you should see a message to that effect.
If you really have no alternative then you can consider using iframes, the src attribute can be outside the current domain and you can parse the information using javascript.
Hope that helps :)

Does $_SERVER['HTTP_X_REQUESTED_WITH'] exist in PHP or not?

All over the Internet, included even here at Stack Overflow, people state that a good way to check if a request is AJAX or not is to do the following:
if (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {...}
However, I don't see $_SERVER['HTTP_X_REQUESTED_WITH'] in the official PHP documentation
And when I try to do the following:
echo $_SERVER['HTTP_X_REQUESTED_WITH'];
Nothing is outputted.
Am I doing something wrong? Because I'd really like to be able to use $_SERVER['HTTP_X_REQUESTED_WITH'] if it's available.
The variables in $_SERVER are not really part of PHP, which is why you won't find them in the PHP documentation. They are prepared by the Web server which passes them on to the scripting language.
As far as I know, the X-Requested-With is sent by the Ajax functions of most major Frameworks but not all (Dojo, for example, added it only two years ago: #5801). As such, and taking into considerations #bobince' comments, it's safe to say it's not generally a 100% reliable method to determine whether a request is an AJAX request or not.
The only 100% secure way is to send a pre-defined flag (e.g. a GET variable) along with the request and for the receiving page to check for the presence of that flag.
don't forget that you can easily spoof any header with cURL like so
curl_setopt($ch,CURLOPT_HTTPHEADER,array("X-Requested-With : XMLHttpRequest"));
$_SERVER keys that start with HTTP_ are generated from HTTP request headers. In this case, the X-Requested-With header.
This header is a standardization-in-progress from all of the AJAX libraries out there.
It won't be documented in the php documentation per-se, but rather in the different AJAX libraries that set this header. Common libraries do sent this header: jQuery, Mojo, Prototype, ...
Usually these library will set the header using
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
Here's a quick function with example usage:
function isXmlHttpRequest()
{
$header = isset($_SERVER['HTTP_X_REQUESTED_WITH']) ? $_SERVER['HTTP_X_REQUESTED_WITH'] : null;
return ($header === 'XMLHttpRequest');
}
// example - checking our active call
if(!isXmlHttpRequest())
{
echo 'Not an ajax request';
}
else
{
echo 'is an ajax request';
}
echo $_SERVER['HTTP_X_REQUESTED_WITH'];
What'd you expect from such a code? Assume you're running it directly from the browser, not using AJAX request. So, how come this header could be set?
Well the Answer to the Ultimate Question of Life, the Universe, and Everything - an HTTP sniffer! Get yourself one and forget of printing $_SERVER variable.
Firebug has one, or you may want to use Fiddler HTTP proxy or LiveHTTPHeaders Mozilla plugin. I'm bored to make links but it easily googled.
So, with HTTP sniffer you can be sure of any HTTP header ever.
Note that you can't prevent any "direct access" by using XHR, as every HTTP request to your server is already "direct".
You have to set it specifically in your ajax request object (that is if you are not using a framework like jQuery), but core Javascript; like so:
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
Where xhr is your request object.
Then, PHP will now receive and set it in the global variable $_SERVER like so:
$_SERVER['HTTP_X_REQUESTED_WITH']
Otherwise $_SERVER['HTTP_X_REQUESTED_WITH'] will always be null.
Note: In your javascript, Please make sure you set headers after the request is open. I mean after xhr.open() method.
You can also blame some browser bugs - see this question and its solution for Firefox
Firefox does not preserve custom headers during Ajax request redirect: an ASP.NET MVC solution
IE also having caching issue which is more serious then detection of request method.
You anyway needs to add cache busters to avoid caching, so why not use another flag to specify the ajax call - or more better you can use different URL like http://ajax.mysite.com/endpoint/sevice?params
I agree Pekka. There is no reliable native method between front side and back side that can auto-detect if a client is really calling an endpoint using AJAX.
For my own use, I have few main ways to check if a client is requesting one of my endpoint:
I can use HTTP_X_REQUESTED_WITH when I'm not in cross domain context.
instead of checking "X-requested-with", I'm checking $_SERVER['HTTP_ORIGIN'] (that is sent from AJAX request) intending to handle cross domain permissions. Most of time, the main reason why I'm checking if a request is an AJAX request, is especially because of cross domain permissions, using this PHP code: header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']); // If this "HTTP_ORIGIN" is in my white list
my APIs expect from the client to explicit, in few cases, the datatype (JSON, HTML etc.) into a GET or a POST var. For example, I check if $_REQUEST['ajax'] is not empty or equal to an expected value.
The best solution to make sure if an HTTP request is truly sent via AJAX is using SESSION checking , you send session_id in a get parameter and you check this session if it's allowed or not !
$headers = apache_request_headers();
$is_ajax = (isset($headers['X-Requested-With']) && $headers['X-Requested-With'] == 'XMLHttpRequest');

Categories