using Guzzle to get request in async mode - php

i have this below code as:
public function postGuzzleRequest()
{
$client = new \GuzzleHttp\Client();
$url = "http://myexample.com/api/posts";
$myBody['name'] = "Demo";
$request = $client->post($url, ['body'=>$myBody]);
$response = $request->send();
dd($response);
}
now i'm trying to use that in async mode

taken directly from the doc:
http://docs.guzzlephp.org/en/stable/quickstart.html
$promise = $client->getAsync('http://httpbin.org/get');
$promise = $client->deleteAsync('http://httpbin.org/delete');
$promise = $client->headAsync('http://httpbin.org/get');
$promise = $client->optionsAsync('http://httpbin.org/get');
$promise = $client->patchAsync('http://httpbin.org/patch');
$promise = $client->postAsync('http://httpbin.org/post');
$promise = $client->putAsync('http://httpbin.org/put');

Related

How do I safe data from an external database using guzzle?

Currently I only can send a get request to the url, but how do i safe the requested data to my database?:
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://xxxx.de/data');
echo $res->getStatusCode();
echo $res->getHeader('content-type')[0];
echo $res->getBody();
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://xxxx.de/data');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();

How to send a correct authorization header for basic authentication using guzzle

How to send a correct authorization header for basic authentication using guzzle
use GuzzleHttp\Client;
$username='EFDEMO';
$password='EFDEMO';
$client = new Client(['auth' => [$username, $password]]);
$res = $client->request('GET', 'https://mb-
rewards.calusastorefront.p2motivate.com/client/json.php/
getMemberAccount');
$res->getStatusCode();
$response = $res->getBody();
echo $response;
the error I am getting
{"statusCode":"Error","error":
{"errorCode":"400","errorMessage":"Authentication Header ID field must
match Basic Authentication Username"}}
Referring to documentation you should pass the auth parameter in request method instead of client's constructor:
$client = new Client();
$res = $client->request(
'GET',
'past-url-here',
['auth' => [$username, $password]]
);
I solved it like below
<?php
require '../x_static_libs/guzzle/vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$username = 'xxxxxx';
$password = 'xxxxxxxx';
$token = 'xxxxxxxxxxxxxxxxxxxx';
$url = 'https://ervb-rewards.com/client/json.php';
$api_token =
base64_encode(json_encode(['id'=>'xxxxxxx','token'=>'xxxxxxxxxxxxxxxxxxxxxx']));
$res = $client->request(
'GET',
$url.'/getMemberAccount',
['auth' => [$username,$api_token]]
);
$jsonData = json_decode($res->getBody(), true);
echo "<pre>";
print_r($jsonData);
echo "</pre>";

Strava Api issue

I'm using this composer package https://github.com/basvandorst/StravaPHP
The OAUTH is working fine and its generating me the JSON with the access token and user id, etc..
But whenever I try to use other function it returns me 404 not found.
Output is this :
{"token_type":"Bearer","access_token":"077058e0c800881c72a4b10a04a520d5898d4e3e","athlete":{"id":35670467,"username":"amir_do","resource_state":2,"firstname":"Amir","lastname":"Do","city":null,"state":null,"country":null,"sex":"M","premium":false,"summit":false,"created_at":"2018-10-13T13:55:41Z","updated_at":"2018-10-13T13:56:25Z","badge_type_id":0,"profile_medium":"https://lh5.googleusercontent.com/-ku6v9lKNgYY/AAAAAAAAAAI/AAAAAAAAAAA/ABtNlbASj8KhClhwnVYVqRrEG2oiYzWPbA/mo/photo.jpg","profile":"https://lh5.googleusercontent.com/-ku6v9lKNgYY/AAAAAAAAAAI/AAAAAAAAAAA/ABtNlbASj8KhClhwnVYVqRrEG2oiYzWPbA/mo/photo.jpg","friend":null,"follower":null,"email":"goncalomaia97#gmail.com"}}
35670467
Client error: `GET https://www.strava.com/api/athletes/35670467/stats?access_token=077058e0c800881c72a4b10a04a520d5898d4e3e` resulted in a `404 Not Found` response: {"message":"Record Not Found","errors":[{"resource":"resource","field":"path","code":"invalid"}]}
And this is my current callback.php page code:
<?php
include 'vendor/autoload.php';
use Strava\API\Client;
use Strava\API\Exception;
use Strava\API\Service\REST;
session_start();
$client = new GuzzleHttp\Client();
global $connect;
require_once("configs/database.php");
$connect = new mysqli($config['database']['host'],$config['database']['user'],$config['database']['pass'],$config['database']['db']);
$code = $_GET['code'];
$state = $_GET['state'];
$scope = $_GET['scope'];
$user = $_SESSION['username'];
$check = $connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $check->fetch_array(MYSQLI_ASSOC);
$apix = $fetch['api'];
$api_secretx = $fetch['api_secret'];
$client = new GuzzleHttp\Client();
$data = [
"client_id" => $apix,
"client_secret" => $api_secretx,
"code" => $code
];
$result = $client->post('https://www.strava.com/oauth/token', ['json' => $data]);
print "<pre>";
print_r( $result->getBody()->getContents() );
print "</pre>";
$bodyb = $result->getBody();
$varx = json_decode((string) $bodyb, true);
$token = $varx['access_token'];
$id = $varx['athlete']['id'];
$_SESSION['token'] = $token;
printf($id);
try {
// REST adapter (We use `Guzzle` in this project)
$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3']);
// Service to use (Service\Stub is also available for test purposes)
$service = new \Strava\API\Service\REST($token, $adapter);
// Receive the athlete!
$client = new Client($service);
$athlete = $client->getAthleteStats($id);
print_r($athlete);
} catch(Exception $e) {
print $e->getMessage();
}
$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3']);
Change that to this (It should be trailing) :
$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3/']);

Setting proxy in Goutte

I've tried using Guzzle's docs to set proxy but it's not working. The official Github page for Goutte is pretty dead so can't find anything there.
Anyone know how to set a proxy?
This is what I've tried:
$client = new Client();
$client->setHeader('User-Agent', $user_agent);
$crawler = $client->request('GET', $request, ['proxy' => $proxy]);
I have solved this problem =>
$url = 'https://api.myip.com';
$client = new \Goutte\Client;
$client->setClient(new \GuzzleHttp\Client(['proxy' => 'http://xx.xx.xx.xx:8080']));
$get_html = $client->request('GET', $url)->html();
var_dump($get_html);
You thinking rigth, but in Goutte\Client::doRequest(), when create Guzzle client
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body
);
options are not passed when create request object. So, if you want to use a proxy, then override the class Goutte\Client, the method doRequest(), and replace this code on
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body,
$request->getParameters()
);
Example overriding class:
<?php
namespace igancev\override;
class Client extends \Goutte\Client
{
protected function doRequest($request)
{
$headers = array();
foreach ($request->getServer() as $key => $val) {
$key = implode('-', array_map('ucfirst', explode('-', strtolower(str_replace(array('_', 'HTTP-'), array('-', ''), $key)))));
if (!isset($headers[$key])) {
$headers[$key] = $val;
}
}
$body = null;
if (!in_array($request->getMethod(), array('GET','HEAD'))) {
if (null !== $request->getContent()) {
$body = $request->getContent();
} else {
$body = $request->getParameters();
}
}
$guzzleRequest = $this->getClient()->createRequest(
$request->getMethod(),
$request->getUri(),
$headers,
$body,
$request->getParameters()
);
foreach ($this->headers as $name => $value) {
$guzzleRequest->setHeader($name, $value);
}
if ($this->auth !== null) {
$guzzleRequest->setAuth(
$this->auth['user'],
$this->auth['password'],
$this->auth['type']
);
}
foreach ($this->getCookieJar()->allRawValues($request->getUri()) as $name => $value) {
$guzzleRequest->addCookie($name, $value);
}
if ('POST' == $request->getMethod() || 'PUT' == $request->getMethod()) {
$this->addPostFiles($guzzleRequest, $request->getFiles());
}
$guzzleRequest->getParams()->set('redirect.disable', true);
$curlOptions = $guzzleRequest->getCurlOptions();
if (!$curlOptions->hasKey(CURLOPT_TIMEOUT)) {
$curlOptions->set(CURLOPT_TIMEOUT, 30);
}
// Let BrowserKit handle redirects
try {
$response = $guzzleRequest->send();
} catch (CurlException $e) {
if (!strpos($e->getMessage(), 'redirects')) {
throw $e;
}
$response = $e->getResponse();
} catch (BadResponseException $e) {
$response = $e->getResponse();
}
return $this->createResponse($response);
}
}
And try send request
$client = new \igancev\override\Client();
$proxy = 'http://149.56.85.17:8080'; // free proxy example
$crawler = $client->request('GET', $request, ['proxy' => $proxy]);
You can directly use in Goutte or Guzzle Request
$proxy = 'xx.xx.xx.xx:xxxx';
$goutte = new GoutteClient();
echo $goutte->request('GET', 'https://example.com/', ['proxy' => $proxy])->html();
Use Same method in Guzzle
$Guzzle = new Client();
$GuzzleResponse = $Guzzle->request('GET', 'https://example.com/', ['proxy' => $proxy]);
You can set a custom GuzzleClient and assign it to Goutte client.
When Guzzle makes the request through Goutte uses the default config. That config is passed in the Guzzle construct.
$guzzle = new \GuzzleHttp\Client(['proxy' => 'http://192.168.1.1:8080']);
$goutte = new \Goutte\Client();
$goutte->setClient($guzzle);
$crawler = $goutte->request($method, $url);
For recent versions use:
Goutte Client instance (which extends Symfony\Component\BrowserKit\HttpBrowser)
use Symfony\Component\HttpClient\HttpClient;
use Goutte\Client;
$client = new Client(HttpClient::create(['proxy' => 'http://xx.xx.xx.xx:80']));
...

Symfony DomCrawler status code not working?

hii this is my php code fore get status on url.
$client = new Client();
$url_to_traverse = 'http://wordcomat.com';
$crawler = $client->request('GET', $url_to_traverse);
$status_code = $client->getResponse()->getStatus();
but i try to found status code of facebook it's not return any thing.
$client = new Client();
$url_to_traverse = 'http://www.facebook.com';
$crawler = $client->request('GET', $url_to_traverse);
$status_code = $client->getResponse()->getStatus();
twitter not working.
$client = new Client();
$url_to_traverse = 'http://www.twitter.com';
$crawler = $client->request('GET', $url_to_traverse);
$status_code = $client->getResponse()->getStatus();
facebook or twitter or linkedin or google is not return any thing but not return any error or warning how can i got status of that links.
thank you.
thy are using https protocol
try the following
$client = new Client();
$url_to_traverse = 'https://www.facebook.com';
$crawler = $client->request('GET', $url_to_traverse);
$status_code = $client->getResponse()->getStatus();

Categories