Current Location: Home> Latest Articles> How to Deploy and Serve Machine Learning Models Using PHP

How to Deploy and Serve Machine Learning Models Using PHP

M66 2025-06-19

Introduction:

With the rapid development of artificial intelligence, machine learning models are becoming increasingly prevalent across various fields. However, for developers, how to efficiently deploy trained machine learning models to online environments and provide service-oriented interfaces remains a pressing issue. This article will explain in detail how to deploy and serve machine learning models using PHP, helping developers implement machine learning functionality within PHP environments.

1. Setting Up the Environment

To deploy machine learning models online and provide service-oriented architecture, the first step is to set up a PHP development environment. Tools like XAMPP and WampServer can be used to create a local PHP development environment, allowing us to write and run PHP code.

2. Preparing the Trained Machine Learning Model

Before constructing the online deployment service, we need to prepare a pre-trained machine learning model. Typically, you can train models using Python or other frameworks and save the trained model as a file. In this example, we will use a simple image classification model and save it as an `.h5` file.
  
import tensorflow as tf  
from tensorflow.keras.models import Sequential  
from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten  
<h1>Build the model</h1>
<p>model = Sequential()<br>
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))<br>
model.add(MaxPooling2D((2, 2)))<br>
model.add(Flatten())<br>
model.add(Dense(10, activation='softmax'))</p>
<h1>Compile the model</h1>
<p>model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])</p>
<h1>Train the model</h1>
<p>...</p>
<h1>Save the model</h1>
<p>model.save('model.h5')<br>

3. Using PHP to Load the Model and Make Predictions

In PHP, we can use third-party libraries to load and use machine learning models trained in Python. Here, we will demonstrate how to use TensorFlow Serving to load the model and make predictions.

First, install the TensorFlow Serving PHP extension. It can be easily done via composer:

  
composer require tensorflow-serving-api-php  

Next, you can write a simple PHP script to load the model and make predictions:

  
<?php  
require 'vendor/autoload.php';  
<p>use TensorFlowServingPredictRequest;<br>
use TensorFlowServingPredictResponse;<br>
use GuzzleHttp\Client;</p>
<p>// Define the request data<br>
$request = new PredictRequest();<br>
$request->setModelSpecName('model');<br>
$request->setModelSpecSignatureName('serving_default');</p>
<p>// Convert the input data<br>
$input = [<br>
'image' => [<br>
'b64' => base64_encode(file_get_contents('image.jpg'))<br>
]<br>
];<br>
$request->setInputs($input);</p>
<p>// Send the request<br>
$client = new Client(['base_uri' => 'http://localhost:8501']);<br>
$response = $client->post('/v1/models/model:predict', [<br>
'headers' => ['Content-Type' => 'application/json'],<br>
'body' => $request->serializeToString()<br>
]);</p>
<p>$response = new PredictResponse($response->getBody()->getContents());</p>
<p>// Get the prediction result<br>
$outputs = $response->getOutputs();<br>
$prediction = reset($outputs)['floatVal'][0];<br>

In the code above, we define a PredictRequest object and set the model name and signature. Then, we convert the input data into the required format and send the request to the TensorFlow Serving REST API. Finally, we extract the prediction result from the returned data.

4. Deploying the PHP Script to an Online Environment

Once the model has been loaded and predictions are being made, you can deploy the PHP script to an online environment and provide a web service interface for external systems to interact with. Common web servers like Apache or Nginx can be used to deploy PHP scripts.

Here is an example of installing and starting Apache on an Ubuntu server:

  
sudo apt-get install apache2  
sudo service apache2 start  

Save the PHP script as a .php file and place it in Apache's web root directory. After that, you can access the corresponding URL to use the machine learning model online.

Conclusion:

This article explains how to deploy and serve machine learning models using PHP. By setting up the PHP development environment, preparing the trained model, loading the model for predictions, and deploying the PHP script to an online environment, developers can easily make machine learning models available as services and provide online prediction capabilities. We hope this guide helps you in deploying machine learning models in a PHP environment.