I am using PHP 7.0.10 on Windows Server and I recently installed the PECL grpc extension because I would like to migrate a call like this one:
$output = shell_exec('grpcurl.exe -insecure -proto extranet.proto -d {\"Usuario\":\"user\",\"Senha\":\"pass\"} www.jucerja.rj.gov.br:9443 extranet.v0.BuscaEmpresa/Login 2>&1');
print_r($output);
to a native one using the grpc extension.
I even tried this lib: https://packagist.org/packages/grpc/grpc and this code:
<?php
include 'vendor/autoload.php';
use \Grpc\BaseStub;
use \Grpc\ChannelCredentials;
$stub = new class extends BaseStub{
function __construct(){
parent::__construct("www.jucerja.rj.gov.br:9443", [
'credentials'=> ChannelCredentials::createInsecure()
]);
}
function serializeToString() {
return new class {
function serializeToString(){
return '{"Usuario":"user","Senha":"pass"}';
}
};
}
function login($deserialize){
$this->_simpleRequest('extranet.v0.BuscaEmpresa/Login', $this->serializeToString(), $deserialize);
}
};
$stub->login(function($data){
var_dump($data);
});
But the result was empty !
So, how can I achieve the same result of shell_exec but using php_grpc?
My Answer:
To translate the grpc call to a native PHP call using the grpc pecl extension, you can follow the steps below:
1. Install the grpc pecl extension for PHP. You can do this by running the following command in your terminal:
pecl install grpc
2. Once the grpc extension is installed, you can use it in your PHP code to make the grpc call. Here is an example of how you can make the grpc call using the grpc pecl extension:
php
// Load the grpc extension
dl('grpc.so');
// Create a new channel to the gRPC server
$channel = new Grpc\Channel('www.jucerja.rj.gov.br:9443', [
'credentials' => Grpc\ChannelCredentials::createInsecure()
]);
// Create a client stub for the gRPC service
$client = new extranet\v0\BuscaEmpresaClient($channel);
// Create a request message
$request = new extranet\v0\LoginRequest();
$request->setUsuario('user');
$request->setSenha('pass');
// Make the gRPC call to the Login method
$response = $client->Login($request);
// Print the response
print_r($response);
?>
In this code snippet, we first load the grpc extension, create a channel to the gRPC server, create a client stub for the gRPC service, create a request message with the user and password, make the gRPC call to the Login method, and finally print the response.
Make sure to replace `extranet\v0\BuscaEmpresaClient` and `extranet\v0\LoginRequest` with the actual client and request classes generated from your proto file.
This should help you achieve the same result as the `shell_exec` call but using the grpc pecl extension in PHP.
Rate this post
3 of 5 based on 7355 votesComments