PHP lithium(li3) how to set up automatic response with JSON - php

I have a lithium app set up that way, so when
return($data)
is used it either can be used in the lithium view.html.php as
echo $data
or if request header "accept" equals "json/javacript" it would return something like
{
data: { a:'b' }
}
automatically.
Unfortunately in the new app that I made as a test app that flow is not happening (and only HTML is always returned).
After doing a little research it seems like that it is supposed to be done automatically if I uncomment
require __DIR__ . '/bootstrap/media.php';
inside bootstrap.php But that didn't work, I still have HTML returned. I downloaded a recent version of the lithium framework(I downloaded it may be 1 or 2 months ago)
Anybody knows if automatic response with JSON requires some set up or not?

taken from http://dev.lithify.me/lithium/tickets/view/353
which is then taken from the lithium docs
To enable automatic content-type negotiation (i.e. determining the content type of the response based on the value of the HTTP Accept header), set the 'negotiate' flag to true. Otherwise, the response will only be based on the type parameter of the request object (defaulting to 'html' if no type is present in the Request parameters)
http://li3.me/docs/lithium/action/Controller::$_render
If you need more help on how to implement leave a comment.

It is also possible to set type to $this->request->accepts() when calling render().
return $this->render(array('type' => $this->request->accepts()));

Related

How to get custom header from HTTP response in Laravel 5?

I'm trying to access a custom header from the Request in Laravel. The header name is "accessing_from". Listing all the headers in Laravel, gives me only the "standard ones", but the one that I've set isn't present in the list. Checking in the browser network tab I can see that the header gets sent. So I'm wondering how to access it from within Laravel.
I'm using Angular2 to make the request with the default http service.
The Laravel's $response->header() dump:
The web inspector's log:
Thanks to anyone!
Are you talking about get parameter or something? If so, use:
request()->accessing_from;
For header you should use:
request()->header('accessing_from');
The working solution for this was the answer (the last one) of daver here:
Laravel get request header
Have you tried simple php?
<?php
// Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE
$headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX'];
Full answer:
https://stackoverflow.com/a/541463/3548658
The docs says:
https://laravel.com/api/5.3/Illuminate/Http/Request.html#method_header
use Request;
Request::header('accessing_from');
getting a custom header in Laravel 5.8.
this should apply to earlier versions as well.
If using a header like X-Requested-With: XMLHttpRequest you may notice that it converts this to HTTP_X_REQUESTED_WITH.
This, in turn, is converted to lower case version for the header() method.
request()->header('x_requested_with');
I would suggest using Accessing-From: admin which will add the apache header HTTP_ACCESSING_FROM. And you will be able to access it via the header function like this...
request()->header('accessing_from');

Posting Data to REST API using JSON and PHP

I've been looking around at similar topics on REST APIs but I am still having some confusion in my project, mostly with the PHP side of things.
USPS provides a REST API with functions that can be called via URL like this: https://epfws.usps.gov/ws/resources/epf/login
To make any call successfully, I have been told that a JSON object must be created and passed as a "POST parameter" with the expected values.
This is the JSON object that needs to be passed in this case:
obj=
{
"login":"loginExample",
"pword":"passwordExample"
}
I have also been given a PHP class that is supposed to manage these calls. This is the login function:
public function login ()
{
// Set up the parameters for a login attempt
$jsonData = array(
'login' => $this->loginUser,
'pword' => $this->loginPass,
);
// Make a login request
$jsonResponse = $this->pullResource
('/epf/login', 'POST', $jsonData);
return $jsonResponse;
}
So I have a few questions regarding this:
The document they sent says
"To make the request calls, a JSON object will need to be created and passed as a POST form parameter obj={jsonObject} for security reasons using content-type “application/x-www-form-urlencoded”."
I know that the login function contains the correct input values that USPS' REST API is wanting, but I'm not sure how to pass them as "obj", or how to apply the "content-type".
I have a "constant" defined at the top of my PHP script that looks like this:
const EPF_BASE_URL = 'https://epfws.usps.gov/ws/resources';
And I noticed in the actual functions that this part of the link is left out and they simply reference '/epf/login' as you can see above. Since "$this" contains lots of different values I'm wondering how it supposedly finds EPF_BASE_URL as needed. Is it similar to how 'using' directives work in C#?
What is the easiest way to call this function and display the result? This is my biggest question. Would I use a separate PHP class with an HTML form? I understand the concept of what it should do but I'm completely lost setting up a development environment for it.
I've been trying all of this with MAMP but would love to know if I'm on the right track or not.
That really depends on their API. Hopefully you get a string back that can be decoded to a JSON object (http://au.php.net/manual/en/function.json-decode.php). Some API might give a simple string that says 'SUCCESS' or 'FAIL'. You've got the code, so take a look at what $this->pullResponse() gives you.
If you've been given a PHP class that is supposed to support the API (hopefully from USPS), then it should already take care of putting the data in the form content, and ensuring is it submitted with the appropriate content-type.
A PHP const is more like a C# static string. It is very likely that the library will use the constant to create the end URL (i.e. EPF_BASE_URL . $resource). If you needed to run against a sand box environment, you could change that constant without having to change all the other code.
That's a very big question, because it depends on how you are programming your application. Procedural, MVC, existing frameworks, etc.
At the very least, you would set the loginUser and loginPass on the instantiated object, and call the login method`. You could then inspect the results, assuming the result is a JSON object, or use your favourite debugging method to see the contents.
I'm having a guess as the USPS API class name.
$uspsApi = new UspsApi();
$uspsApi->loginUser = 'username';
$uspsApi->loginPass = 'password';
$result = $uspsApi->login();
echo print_r($result, true);

Set Request (not Response) Headers in Laravel 5 for Non-Ajax Routes

I am actually completely baffled that this is such a difficult task to accomplish and/or find any relevant information about. My guess is that it must be something SO simple, that no one has to ask about it (except for me! :-) ), so I am hoping that someone can easily point me in the right direction...
I need to set headers in my Requests - not in my Responses (I've got that part handled), and not for Ajax routes (I've got that part handled as well). How on Earth do I accomplish this on internal app routes in Laravel 5.1?
Essentially, I need to attach an 'Authorization' header to certain Requests. (i.e.
$request->headers->set('Authorization', 'my-authorization-token');
)This line of code does not work, however. No matter where I put it. It doesn't work from middleware. It doesn't work from routes.php. It doesn't work from my controllers... it just simply does not work period. (For the sake of clarity, '$request' is 'Illuminate\Http\Request').
What am I missing? Where/How can I set request headers before a request is sent? Please help! Thanks in advance.
Some of the answers here might give you an idea, you could adapt them for the request: Where can I set headers in laravel
This also looks relevant: Laravel 5 / Lumen Request Header?
The request is sent from the client to the server (i.e. your Laravel app). So you set the request headers on the client site using Javascript.
The Laravel documentation has an example of setting the X-CSRF-TOKEN header using jQuery.
$.ajaxSetup({
headers: {
'X-MY-HEADER': 'whateveryouwant
}
});
Using VueJS it would look like this
Vue.http.headers.common['X-MY-HEADER'] = 'whateveryouwant';
You need to create a new request object and then set the header like this:
// e.g., Inside controller method
$request = new \Illuminate\Http\Request();
$request->setMethod('POST'); // or whatever your request type is
$request->header('Authorization', 'my-authorization-token');

How does get_headers work in the background

I tryied searching for this and I belive I alredy know the answer but it's crusal that I'm not wrong, so here I go..
When calling get_headers, will I retrieve the whole file even though the function only returns the headers or will it retrieve, as expected, only the headers and nothing else?
I'm guessing the last but if I'm wrong this will cause some serious problems..
Also I noticed that there is a global setting I can change to send a HEAD request instead of the default GET request, witch is why I'm asking my self whats really going on.
Edit
Maybe this function is a better alternative? stream_get_meta_data or do they actually do the same thing?
You could also take a look at the source code, if you are familiar with C.
The function is defined here. I quickly looked over this, and it seems it is a header-only request, see line 715:
STREAM_ONLY_GET_HEADERS
GET
Requests a representation of the specified resource. Requests using
GET should only retrieve data and should have no other effect. (This
is also true of some other HTTP methods.) The W3C has published
guidance principles on this distinction, saying, "Web application
design should be informed by the above principles, but also by the
relevant limitations."
HEAD
Asks for the response identical to the one that would correspond to a
GET request, but without the response body. This is useful for
retrieving meta-information written in response headers, without
having to transport the entire content.
Wikipedia/Hypertext_Transfer_Protocol
The PHP-docs clearly states that normal get_headers() uses a GET-request, but you can force it to use HEAD instead, like this:
<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers('http://example.com');
?>
Unfortunaley you're right, just read the PHP manual:
get_headers() returns an array with the headers sent by the server in response to a HTTP request.
Also take a look at the examples.
Okay, next time I should spend more attention to the question formulation.
Yeh, if the request type is set to GET (standard) you will get the whole content. You could change it to HEAD, but this is not what you want.

Receiving and handling a GET request in PHP

I'm trying to replace RSS polling with PubSubHubbub on my site. I'm able to use the subscriber library that google offers to send the subscription request. From the code it looks like it sends a post request via cURL with the RSS URL and a callback URL.
So this is where I need some direction:
In order to complete the subscription request my callback URL has to receive a GET request and then echo back a value from the GET request along with a 200 response. How do I get the parameters from the GET request? Is the echo done again via cURL? If so what option should include the 200 response?
This very simple script should be a start:
echo $_GET["request_name"];
this will output the GET parameter request_name and (implicitly) send a 200.
It's also a good idea to explicitly declare a content type before echoing, to prevent the default content type (usually "text/html") from kicking in:
header("Content-type: text/plain");
Note that when echoing external data, you may need to sanitize the output first - if the for example the output format is HTML, you would want to do something like echo htmlspecialchars($_GET["request_name"]); to prevent Cross-Site Scripting.
There was recently a thread on the php-dev mailing list about this. The reason you can't access 'hub.challenge' in the $_GET superglobal is due to register_globals. Basically PHP cleans up any argument names before creating the superglobals. Any dots will be converted to underscores. It's looking to be 'fixed' in PHP 6, but not before due to BC issues.
Here's the thread about it.

Categories