PHP

gRPC Server with PHP

CK CK 3788 
Created at  
509 0 0

The easiest approach to implement a gRPC server with PHP is using the grpc/grpc extension. This extension provides the necessary bindings for compiling and running gRPC services. You'll define your service using the Protocol Buffer language (.proto), generate PHP code from the .proto file using the Protocol Buffer compiler (protoc), then implement the server-side logic within the generated PHP classes, handling incoming requests and responding according to your service definition. Finally, you'll create a server instance, register your service implementation, and start listening for connections on a specified port.

Implementing a gRPC server in PHP is straightforward when using the gRPC PHP extension. Here's the easiest approach:


1. Install Prerequisites

  • Install PHP: Ensure you have PHP 7.4+ installed.
  • Install Composer: PHP’s dependency manager.
  • Install gRPC PHP Extension:
    • On Linux:

      pecl install grpc
      
    • On macOS (Homebrew):

      brew install grpc
      pecl install grpc
      
    • Verify the extension:

      php -m | grep grpc
      

2. Install Required Packages

Add the grpc and protobuf packages to your project using Composer:

composer require grpc/grpc google/protobuf

3. Define the .proto File

Create a proto directory and add your .proto definition, e.g., proto/helloworld.proto:

syntax = "proto3";

package helloworld;

// The greeting service definition.
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

4. Generate PHP Classes from .proto

Install the Protocol Buffers compiler (protoc) and the PHP plugin.

  • Install protoc:
    • On macOS: brew install protobuf
    • On Ubuntu: sudo apt install protobuf-compiler
  • Install PHP plugin for protoc:

    composer global require grpc/protoc-gen-php-grpc
    

Ensure the plugin is in your $PATH:

export PATH="$PATH:$HOME/.composer/vendor/bin"
  • Generate PHP files:

    protoc --proto_path=proto --php_out=./generated --grpc_out=./generated --plugin=protoc-gen-grpc=$(which protoc-gen-php-grpc) proto/helloworld.proto
    

This generates GreeterClient.php and GreeterServer.php in the generated directory.


5. Implement the Server

Create a PHP file (e.g., server.php) and implement the service:

<?php
require 'vendor/autoload.php';
require 'generated/GPBMetadata/Helloworld.php';
require 'generated/Helloworld/GreeterClient.php';
require 'generated/Helloworld/GreeterServer.php';

use Helloworld\GreeterServer;
use Helloworld\HelloReply;
use Helloworld\HelloRequest;
use Grpc\Server;

class GreeterImpl extends GreeterServer
{
    public function SayHello(HelloRequest $request): HelloReply
    {
        $response = new HelloReply();
        $response->setMessage("Hello, " . $request->getName());
        return $response;
    }
}

// Create the server
$server = new Server();
$server->addHttp2Port('0.0.0.0:50051');
$server->handle(new GreeterImpl());

echo "Server running at 0.0.0.0:50051\n";
$server->run();

6. Run the Server

Start the server:

php server.php

You should see:

Server running at 0.0.0.0:50051

7. Implement the Client

Create a PHP file (e.g., client.php) to call the server:

<?php
require 'vendor/autoload.php';
require 'generated/GPBMetadata/Helloworld.php';
require 'generated/Helloworld/GreeterClient.php';
require 'generated/Helloworld/HelloRequest.php';

use Helloworld\GreeterClient;
use Helloworld\HelloRequest;

$client = new GreeterClient('localhost:50051', [
    'credentials' => \Grpc\ChannelCredentials::createInsecure(),
]);

$request = new HelloRequest();
$request->setName('World');

list($response, $status) = $client->SayHello($request)->wait();

if ($status->code === \Grpc\STATUS_OK) {
    echo "Response: " . $response->getMessage() . "\n";
} else {
    echo "Error: " . $status->details . "\n";
}

8. Run the Client

Start the client:

php client.php

You should see:

Response: Hello, World

Summary

  • Server: server.php runs the gRPC server.
  • Client: client.php calls the gRPC server.
  • Tools Used: Composer for dependencies, Protocol Buffers for gRPC definitions, and the gRPC PHP extension for communication.

This is the easiest and cleanest way to set up a gRPC server with PHP!

Tags PHP gRPC gRPC gRPC Extension gRPC Server protoc Facebook X
Comments 0
Similar posts
  1. Simple gRPC server based on Python
    398
  2. gRPC library for Rust
    345
  3. gRPC - Open-source Universal RPC Framework developed by Google
    770
  4. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    175
  1. When you Postgresql Module is not able to open connection : Doubt your libpq version
    480
  2. How to Get a YouTube Channel ID from a URL in PHP
    1,030
  3. Building a MCP server in PHP
    638
  4. PHP 7 vs PHP 8
    1,254
  5. Upgrading PHP 7.4 to PHP 8.1 in CentOS 7
    653
  6. PHP Code to Fetch current Coinbase Assets (Balances)
    444
  7. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    366
  8. Google Single Sign-On implementation with PHP
    1,381
  9. PHP Superglobal Variables do not require additional syntax to access it
    2,656
  10. Run Python Code with Virtual Environment in PHP
    675
  11. PHP Simplified Operators
    318
  12. PHP Heredoc (aka Nowdoc)
    447
  13. PHP Post Processing by disconnecting HTTP connection and continuing the remaining logics
    1,824
  14. WordPress Remote Posting with PHP
    1,700
  15. Google BigQuery Example to converted Nested FIelds in JSON
    461
  16. Verifying Apple In-App Purchase validation receipt with PHP
    1,803
  17. Useful code for file-based Unit Test in PHP
    507
  18. Function Overloading Implementation in PHP with Magic Mathods
    1,764
  19. PHP Magic - the Null Coalescing Operator (??) - return the value if the give variable is NULL
    1,680
  20. How do I find php.ini on Mac?
    495
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,904
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232