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 :)
Related
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 try to download content of the web page with web scraping but on of the main problems is I can not bypass redirect of websites. for example when I try login to the website and submit the login form. I see waiting page and just waiting page.
but in browser after waiting page I redirect to profile page
I downloaded goutte and created my script but in submit form I have problem because when I submit wrongdoer password or username I will see incorrect password but when I enter correct username and password I will see waiting image to redirect
First Edit
according to the update response my code is
<?php
require_once 'vendor/autoload.php';
use Goutte\Client;
$client = new Client();
$url = 'https://egghead.io/users/sign_in';
$username = 'xxxx';
$password = 'xxxx';
$crawler = $client->request('GET', $url, [
'allow_redirects' => true
]);
$form = $crawler->selectButton('Sign In')->form();
$crawler = $client->submit($form, array('user[email]' => $username, 'user[password]' => $password));
$crawler->filter('body')->each(function ($node){
print $node->html();
});
Goutte will automatically follow redirects unless you tell it not to. You can customize the redirect behavior using the allow_redirects request option.
Set to true to enable normal redirects with a maximum number of 5
redirects. This is the default setting.
Set to false to disable redirects.
Pass an associative array containing the 'max' key to specify the
maximum number of redirects and optionally provide a 'strict' key
value to specify whether or not to use strict RFC compliant redirects
(meaning redirect POST requests with POST requests vs. doing what
most browsers do which is redirect POST requests with GET requests).
ref:
http://docs.guzzlephp.org/en/latest/quickstart.html#redirects
Update:
$crawler = $client->request('GET', 'http://egghead.io', [
'allow_redirects' => true
]);
$crawler = $client->click($crawler->selectLink('Sign in')->link());
$form = $crawler->selectButton('Sign in')->form();
$crawler = $client->submit($form, array('login' => 'fabpot', 'password' => 'xxxxxx'));
$crawler->filter('.flash-error')->each(function ($node) {
print $node->text()."\n";
});
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);
I am newbie to drupal and node.js. I am connecting drupal with node.js server. What I am trying to do is that to get the cookie from the the node.js server response and I need to set these cookies over to the next request to the node.js server
function sample_submit($form, &$form_state) {
$request_url = "http://localhost/api/authenticate"; //Link to Node.Js server
$sig = hash_hmac('sha512', 'secret', 'secret');//hashed the api key using sha512 algoritham
$options = array(
'method' => 'POST',
'data' => 'apikey='.$sig,//api key for authenticaton between nodejs and drupal application
'timeout' => 15,
'headers' => array('Content-Type'=> 'application/x-www-form-urlencoded')
);
$result = drupal_http_request($request_url, $options);
}
I am authenticating the request with an api key with node.js server. node.js server create a session cookie with the help of passportjs module. I want get the cookie from the the node.js server and pass the cookie with the next request. That is I want get the cookie from the above function and then to send the cookie along with the request in below function so that only node.js server can authenticate with drupal app.
function sample_submit1($form, &$form_state) {
$request_url = "http://localhost/login"; //Link to Node.Js server
$options = array(
'method' => 'GET',
'timeout' => 15,
'headers' => array('Content-Type'=> 'application/x-www-form-urlencoded')
);
$result = drupal_http_request($request_url, $options);
drupal_set_message(t($result->data));
Is there any way or any better way to do this? Any insight into this would highly be appreciated. Thank you.
I need to connect to a web service that requires authentication credentials in the form of a plain text user name and password.
I have a basic understanding of SOAP and have managed to connect to other open web services that do not require a username or password using NuSOAP.
The following was sent to me:
<?php
// Set up security options
$security_options = array("useUsernameToken" => TRUE);
$policy = new WSPolicy(array("security" => $security_options));
$security_token = new WSSecurityToken(array(
"user" => "xxx",
"password" => "xxx",
"passwordType" => "basic"));
// Create client with options
$client = new WSClient(array("wsdl" => "https://xxx.asmx?wsdl",
"action" => "http://xxx",
"to" => "https://xxx",
"useWSA" => 'submission',
"CACert" => "cert.pem",
"useSOAP" => 1.1,
"policy" => $policy,
"securityToken" => $security_token));
// Send request and capture response
$proxy = $client->getProxy();
$input_array = array("From" => "2010-01-01 00:00:00",
"To" => "2010-01-31 00:00:00");
$resMessage = $proxy->xxx($input_array);
?>
After some research I understand that the above implementation uses wso2. I need to be able to do this without using wso2.
I have tried my best to look for resources (Google, forums, etc) about the above but haven't been able to find anything. I have read some tutorials on SOAP and have been able to set up a SOAP client using PHP but cannot get my head around all the authentication and "policies".
An explanation of how to achieve this and maybe some links to further reading about this would be very much appreciated as I am tearing my hair out! Ideally I would like some links to resources for an absolute beginner to the SOAP authentication.
Thanks. P.S some of the links/credentials in the above could have been xxx'd for privacy.
If you have the SOAP extension enabled in php (php version >= 5.0.1), you can use the SoapClient class to process your request. To authenticate, you can pass the username and password to the class with the target URL:
$soapURL = "https://www.example.com/soapapi.asmx?wsdl" ;
$soapParameters = Array('login' => "myusername", 'password' => "mypassword") ;
$soapFunction = "someFunction" ;
$soapFunctionParameters = Array('param1' => 42, 'param2' => "Search") ;
$soapClient = new SoapClient($soapURL, $soapParameters);
$soapResult = $soapClient->__soapCall($soapFunction, $soapFunctionParameters) ;
if(is_array($soapResult) && isset($soapResult['someFunctionResult'])) {
// Process result.
} else {
// Unexpected result
if(function_exists("debug_message")) {
debug_message("Unexpected soapResult for {$soapFunction}: ".print_r($soapResult, TRUE)) ;
}
}
If you're not sure about the functions you can call, you can view the target URL (e.g. ending in ".asmx?wsdl") in your browser. You should get an XML response that tells you the available SOAP functions you can call, and the expected parameters of those functions.
Check out the soap_wsse library