I need to send a request with custom cookies.
I have tried to set cookieJar like this:
$cookieJar = CookieJar::fromArray(array($cookieName=>$cookieStr),
'api.mobra.in');
$res = $this->guzzleClient->request($requestMethod, $url,
[
'cookies' => [$cookieJar]
]
);
But it is getting an error
cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface
Please suggest example or explain in details.
I gone through documents but they have not mentioned in detail.
Thank you!
use GuzzleHttp\Cookie\CookieJar;
$cookieJar = CookieJar::fromArray([
'cookie_name' => 'cookie_value'
], 'example.com');
$client->request('GET', '/get', ['cookies' => $cookieJar]);
You can read the documentation here.
One more way to add a cookie to the request with Guzzle:
$url = 'https://www.example.com';
$request_options = [
'headers' => ['Cookie' => 'COOKIE_NAME=VALUE']
];
$response = $this->httpClient->request('GET', $url, $request_options);
Guzzle can maintain a cookie session for you if instructed using the cookies request option. When sending a request, the cookies option must be set to an instance of GuzzleHttp\Cookie\CookieJarInterface.
// Use a specific cookie jar
$jar = new \GuzzleHttp\Cookie\CookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
'cookies' => $jar
]);
You can set cookies to true in a client constructor if you would like to use a shared cookie jar for all requests.
// Use a shared client cookie jar
$client = new \GuzzleHttp\Client(['cookies' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');
Check too the full quickstart.
For sending cookie with Guzzle Http in laravel you can use this sample code:
//your address
$address = "http://example.com/xyz";
//your cookie
$coockie = ['Cookie' => "Key=Value"];
//your request
$res = Http::withOptions([
'headers' => $coockie
])->get($address);
Related
I'm currently developping an application in Symfony using Guzzle. I succesfully created a service where I make my requests (one request to get a list of enterprises, another to get user infos, ...) but I have issues regarding cookies in Guzzle. I've got to say I'm a newbie regarding API so I'm learning as I read the documentation but found nothing interesting for the moment. I've tried everything found on the internet so far but didn't get the result I wanted.
When I make a request, I get a property "Set-Cookie" in my response that I need to put in my next requests. The "Set-Cookie" property is something like "EfficySession=XX-XXXXX~XXXXXXXX-XXXXXXXX; path=/crm/; expires=Wed, 13 Oct 2021 23:22:14 GMT; HttpOnly".
So far this is where I am :
I create my client in the construct in order to be able to use the same client in every method :
public function __construct()
{
$this->client = new Client(["base_uri" => "BASE_URI", "allow_redirect" => true]);
}
And this is my test request to try setting my cookies right :
public function testFunction()
{
$json = json_encode([
[
"#name" => "api",
"#func" => [
[
"#name" => "currentuserfullname"
]
]
]
]);
$jar = new CookieJar();
$headers = [
'X-Efficy-ApiKey' => $this->apiKey,
'X-Efficy-Logoff' => 'false',
'Content-Type' => 'application/json'
];
$options = ["headers" => $headers, "body" => $json, "cookies" => $jar];
$response = $this->client->request('GET', 'json', $options);
$cookieParser = new SetCookie();
$cookie = $cookieParser->fromString($response->getHeader("Set-Cookie")[0]);
$cookie->setDomain('DOMAIN');
$this->jar->setCookie($cookie);
return json_decode($response->getBody()->getContents())[0]->{'#func'}[0];
}
But my cookies doesn't seem to be stored since I always get the property "Set-Cookie" in my response's headers... I think I've tried everything, from using SessionCookieJar to using CookieJar but nothing seems to be working.
Maybe I don't understand things the right way but as I said above, I'm just starting with API so sorry if you see big mistakes in my code.
I'm attempting to retrieve a file attachment with Guzzle. The file isn't available directly through an endpoint, but the download is initiated via the end point and downloaded to my browser. Can I retrieve this file with Guzzle?
I successfully login to the site, but what is saved to my file is the html of the site not the download. The file contents seems to come through when I make the request with insomnia rest client, but not with Guzzle.
$client = new GuzzleHttp\Client();
$cookieJar = new \GuzzleHttp\Cookie\CookieJar();
$response = $client->post('https://test.com/login', [
'form_params' => [
'username' => $username,
'password' => $password,
'action' => 'login'
],
'cookies' => $cookieJar
]);
$resource = fopen(__DIR__.'/../../feeds/test.xls', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$response = $client->request('GET', 'https://test.com/download', ['sink' => $stream]);
If you want to perform an authentication step and then a download step, you'll need to make sure the cookies are persisted across both requests. Right now you're only passing your $cookieJar variable to the first one.
The explicit way of doing this would be to add it to the options for the second request:
['sink' => $stream, 'cookies' => $cookieJar]
but it might be easier to take advantage of the option in the client constructor itself:
$client = new GuzzleHttp\Client(['cookies' => true);
That means that every request (with that client) will automatically use a shared cookie jar, and you don't need to worry about passing it into each request separately.
You should send Content-Disposition header in order to specify that the client should receive file downloading as a response. According to your GET HTTP request which will capture the contents into the $stream resource, finally you can output these contents to browser with stream_get_contents.
<?php
// your 3rd party end-point authentication
...
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="test.xls"');
$resource = fopen(__DIR__.'/../../feeds/test.xls', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$response = $client->request('GET', 'https://test.com/download', ['sink' => $stream]);
echo stream_get_contents($stream);
I need to POST data to an AWS API Gateway URL.
I have no clue how to do this with PHP. (Like I cannot imagine it to be this difficult.)
Any help would be appreciated.
I need to send a JSON body to an API Gateway API (IAM) the SDK does not seem to have any documentation that can help me.
I need to POST this:
{
"entity": "Business",
"action": "read",
"limit": 100
}
To an API gateway endpoint using sig 4
Example endpoint (https://myendpoint.com/api)
I really struggled with this and finally managed to clear it with the following approach:
require './aws/aws-autoloader.php';
use Aws\Credentials\Credentials;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Signature\SignatureV4;
use Aws\Credentials\CredentialProvider;
$url = '<your URL>';
$region = '<your region>';
$json = json_encode(["Yourpayload"=>"Please"]);
$provider = CredentialProvider::defaultProvider();
$credentials = $provider()->wait();
# $credentials = new Credentials($access_key, $secret_key); # if you do not run from ec2
$client = new Client();
$request = new Request('POST', $url, [], $json);
$s4 = new SignatureV4("execute-api", $region);
$signedrequest = $s4->signRequest($request, $credentials);
$response = $client->send($signedrequest);
echo($response->getBody());
This example assumes you are running from an EC2 or something that has an instance profile that is allowed to access this API gateway component and the AWS PHP SDK in the ./aws directory.
You can install AWS php sdk via composer composer require aws/aws-sdk-php and here is the github https://github.com/aws/aws-sdk-php . In case you want to do something simple or they don't have what you are looking for you can use curl in php to post data.
$ch = curl_init();
$data = http_build_query([
"entity" => "Business",
"action" => "read",
"limit" => 100
]);
curl_setopt_array($ch, [
CURLOPT_URL => "https://myendpoint.com/api",
CURLOPT_FOLLOWLOCATION => true
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data
]);
$response = curl_exec($ch);
$error = curl_error($ch);
With Guzzle (version 3), I'd like to specify the body of a POST request in "raw" mode. I'm currently trying this:
$guzzleRequest = $client->createRequest(
'POST',
$uri,
null,
'un=one&deux=two'
);
But it kind of doesn't work. If I dump my $guzzleRequest I can see that postFields->data is empty. Using $guzzleRequest->setBody() afterwards doesn't help.
However if I specify the body as ['un'=>'one', 'deux'=>'two'], it works as expected.
How can I specify the body of the request as 'un=one&deux=two'?
First I would highly recommend that you upgrade to Guzzle 6 as Guzzle 3 is deprecated and EOL.
It has been a long time since I used Guzzle 3 but I do believe you want the following:
$request = $client->post(
$uri,
$header = [],
$params = [
'un' => 'one',
'deux' => 'two',
]);
$response = $request->send();
Guzzle will automatically set the Content-Type header.
More information is available with the Post Request Documentation.
In response to your comment:
$request = $client->post(
$uri,
$headers = ['Content-Type' => 'application/x-www-form-urlencoded'],
EntityBody::fromString($urlencodedstring)
)
For this, reference: EntityBody Source and RequestFactory::create()
Project is consuming URL API which is updating the data every seconds. By using Guzzle 6, How can i refresh the data in browser without AJAX?
...
...
$un = 'admin';
$pa = 'password';
$base_uri = 'http://example.com:82';
$uri1 = 'api/instant/connectopc';
$uri2 = 'api/instant/displaydata?site=SITE';
$cookieFile = 'jar.txt';
$cookieJar = new FileCookieJar($cookieFile, true);
$client = new Client([
'base_uri' => $base_uri,
'auth'=>[$un, $pa],
'cookie'=>$cookieJar,
'curl' => [
CURLOPT_COOKIEJAR => 'jar.txt',
CURLOPT_COOKIEFILE => 'jar.txt'
],
]);
$connect = $client->get($uri1);
//live data to be refresh every seconds. How to do?
$live= $client->get($uri2, ['cookies' => $cookieJar]);
...
How to accomplish live data streaming?
You cannot do any live streaming from the same page once browser has closed the connection. You have to open another connection. Via Ajax or another technology like WebSockets for example if you need realtime data exchange.
You can't do live streaming with PHP .. You need to use a programming language like NodeJS :) .. PHP ends the connection at the end :)