I'm trying to get the hostname from an HTTP request using Laravel 5, including the subdomain (e.g., dev.site.com). I can't find anything about this in the docs, but I would think that should be pretty simple. Anyone know how to do this?
Good news! It turns out this is actually pretty easy, although Laravel's Request documentation is a bit lacking (the method I wanted is inherited from Symfony's Request class). If you're in a controller method, you can inject the request object, which has a getHttpHost method. This provides exactly what I was looking for:
public function anyMyRoute(Request $request) {
$host = $request->getHttpHost(); // returns dev.site.com
}
From anywhere else in your code, you can still access the request object using the request helper function, so this would look like:
$host = request()->getHttpHost(); // returns dev.site.com
If you want to include the http/https part of the URL, you can just use the getSchemeAndHttpHost method instead:
$host = $request->getSchemeAndHttpHost(); // returns https://dev.site.com
There two ways, so be careful:
<?php
$host = request()->getHttpHost(); // With port if there is. Eg: mydomain.com:81
$host = request()->getHost(); // Only hostname Eg: mydomain.com
laravel 5.6 and above
request()->getSchemeAndHttpHost()
Example of use in blade :
{{ request()->getSchemeAndHttpHost() }}
You can use request()->url();
Also you can dump the complete request()->headers();
And see if that data is useful for you.
Related
I've been dealing with the Laravel/Osiset-Shopify framework for some time and even after a long research there are things that I don't understand yet.
For example, if I want to fetch my webhooks, it is relatively cumbersome
Auth::user()->api()->rest('GET', '/admin/api/2021-04/webhooks.json')['body']
There is a function getWebhooks() under \osiset\laravel-shopify\src\ShopifyApp\Services\ApiHelper.php which I would much rather use.
I came across this documentation from Osiset, for which I don't know how to use it.
I tried to load the service use Osiset\ShopifyApp\Services\ApiHelper; and get the output data dd(ApiHelper::getWebhooks([]));. However, I get the error message Non-static method Osiset\ShopifyApp\Services\ApiHelper::getWebhooks() cannot be called statically.
Also
$foo = new ApiHelper;
dd( $foo->getWebhooks() );
did not lead to any result: Call to a member function rest() on null.
Can someone show me how to access Osiset's internal functions and use the documentation properly?
You can use this documentation
and for the webhooks.json, You can use this to get the results $userId will be the user's primary key.
$shop = User::find($userId);
$method = 'GET';
$url = '/admin/api/2021-04/webhooks.json';
return $shop->api()->rest($method, $url, []);
I played around with the PHP 7.2 runtime and HTTP trigger on Alibaba Cloud Function Compute. The basic example in the documentation is the following:
<? php
use RingCentral\Psr7\Response;
function handler($request, $context): Response{
/*
$body = $request->getBody()->getContents();
$queries = $request->getQueryParams();
$method = $request->getMethod();
$headers = $request->getHeaders();
$path = $request->getAttribute("path");
$requestURI = $request->getAttribute("requestURI");
$clientIP = $request->getAttribute("clientIP");
*/
return new Response(
200,
array(
"custom_header1" => "v1"
),
"hello world"
);
}
This works quite well. It's easy to get the query parameters from an URL. But the body content is only available in a whole string with
$request->getBody()->getContents();
Although the documentation says that the $request parameter follows the PSR-7 HTTP Message standard, it is not possible to use $request->getParsedBody() to deliver the values submitted by POST method. It didn't work as expected - the result remains empty.
The reason is the underlying technology. Alibaba Cloud Function Compute makes use of the event-driven React PHP library to handle the requests (you can check this by analyzing the $request object). So the $_POST array is empty and there is no "easy way to get POST data".
Luckily, Alibaba's Function Compute handler provides the body content by $request->getBody()->getContents(); as a string like
"bar=lala&foo=bar"
So a solution seems easiser than thought at the beginning, you can e.g. use PHP's own parse_str() function:
$data = [];
$body = $request->getBody()->getContents();
parse_str($body,$data);
If you place this snippet in the handler function, the POST variables are stored in the $data array and ready for further processing.
Hope that this helps somebody who asked the same questions than I. :-)
Kind regards,
Ralf
As you can see in the documentation you need to add a RequestBodyParserMiddleware as middleware to get a parsed PSR-7 request. It seems you didn't do that.
Also keep in mind that only the Content-Types: application/x-www-form-urlencoded and multipart/form-data are supported here. So make sure the client need to send these headers so the request can be parsed. If it's another Content-Type you need to use another middleware.
See: https://github.com/reactphp/http#requestbodyparsermiddleware for more information.
I hope this helps!
#legionth: I apologize that I didn't use the comment feature here, but my answer is too long. :-)
Thanks a lot for your comments - the usage of RequestBodyParserMiddleware is a great solution if you can control the server code. But in the context of Alibaba Cloud Function Compute service this seems not possible. I tried to find out more information about the invocation process - here are my results:
Function Compute makes use of the Docker image defined in https://github.com/aliyun/fc-docker/blob/master/php7.2/run/Dockerfile .
In the build process they download a PHP runtime environment from https://my-fc-testt.oss-cn-shanghai.aliyuncs.com/php7.2.tgz . (I didn't find this on GitHub, but the code is public downloadable.)
A shell script start_server.sh starts a PHP-CGI binary and runs a PHP script server.php.
In server.php a React\Http\Server is started by:
$server = new Server(function (ServerRequestInterface $request) {
[...]
});
[...]
$socket = new \React\Socket\Server(sprintf('0.0.0.0:%s', $port), $loop);
$server->listen($socket);
$loop->run();
As seen in the Function Compute documentation (& example of FC console), I can only use two functions:
/*
if you open the initializer feature, please implement the initializer function, as below:
*/
function initializer($context) {
}
and the handler function you can find in my first post.
Maybe Alibaba will extend the PHP runtime in future to make it possible to use a custom middleware, but currently I didn't find a way to do this.
Thanks again & kind regards,
Ralf
I am always getting the this error.
{"status":false,"error":"Unknown method."}
But all syntax are correct from my side. because everything is working fine on the browser but same URL integration on the devices gives the 'unknown method error'.
I am using this 'get' method. Sample URL
SITEURL/api/login/test?req_type=custom
Am I missing something while integrating? Perhaps a setting? I have just included the library and rest config file.
I think your problem is the name of controller is the same with the name of method try to make a test:
if the name of your controller is:
class Test extends REST_Controller{
//your method name is different from the name of controller class
public function testget_get(){
echo $this->response(array('test'=> 'test'), 200);
}
}
I have experienced this problem on hmvc structure.
You also need to check that from device which method your are getting means they are sending 'POST' or 'GET' so you can update your function name accordingly.
In my case I have done the function name as _get to the methods but from device methods of sending parameter is 'POST' which I am trying to access as 'GET'.
So please cross check this once.
When you create a method with the library, you need to append the type of request you are going to make to it.
So, if your method is test, and you are making a GET request to it, it needs to look like this:
function test_get(){
...
}
Same with POST requests
function test_post(){
...
}
Same with PUT, and DELETE as well.
NB This is only a guess since you didn't include any of your code for some reason.
I'm using Restler to develop a REST api and I need to get the requested service from the iAuthenticate implementation.
So far I have managed to get here:
$m = preg_match('/.+?\/(?P<api>.+?)\/(?P<service>\w+)/', $_SERVER['REQUEST_URI']);
and $_SERVER['REQUEST_URI'] has this form: /somedir/apiclass/requestedservice?...
I've tried my regex here: http://www.spaweditor.com/scripts/regex/index.php with my actual uri
and it works perfectly. When I try to parse the request url inside my iAuthenticate implementation it just don't work.
Does anybody know how to enable regex within restler iAuthenticate implementation? How can I display errors in Restler instead of a blank page?
Thanks!
[EDIT]
I wasn't passing the variable to store the match object, preg_match recieves a third argument to store it and just returns a boolean. Case closed.
I finally solved it like this:
preg_match('/.+?\/(?P<api>.+?)\/(?P<service>\w+)/', $_SERVER['REQUEST_URI'], $mo);
$api = $mo['api'];
$service = $mo['service'];
I am trying to write a short Rest Service with Zend Framework. But the documentation is not the best at this Part.
I have an ApiController extended Zend_Rest_Controller with all needed abstract methods. My goal is to get Post data and return something.
My client looks like this:
public function indexAction()
{
$url = 'http://localhost/url/public/api';
$client = new Zend_Rest_Client();
$client->setUri($url);
$client->url = 'http://www.google.de';
$result = $client->post();
}
but the provided "$client->url" is not inside the post array on Server side. Does I have to use Zend Rest Server inside the postAction on my ApiController?
If someone has an example how to send and to get the data with Zend Rest, that would be great.
Maybe this tutorial Create RESTful Applications Using The Zend Framework can help.
Have you tried setting it to access 127.0.0.1 rather than localhost? I know this can cause issues sometimes.