Tag Archives: #php

Installing Elasticsearch Client on PHP

For a simple demonstration of using Elasticsearch programmatically as a web app, it’s a little more practical to use PHP as a starting point to learn how to connect and display search results. As a guideline, the quick-start instruction from Elastic site is a starting point. To expand (possibly complete) the out of the box setup, below are the steps to setup PHP to enable Elasticsearch support.

First, install the PHP Curl support for Apache on Linux:

apt-get -y install php-curl

Setup the PHP Composer in the doc-root folder, as outlined from elasticsearch-php github. Setup the php libraries via Composer:

php composer.phar init
curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev

Be sure to get the dependency package “elasticsearch/elasticsearch” and use the latest version as default. Note, skip the development package as it’s not really necessary.

Then, edit the composer.json file to include the directive:

   "require": {
            "elasticsearch/elasticsearch": "~6.0"

Finally, create a test page to see if it can connect to the Elasticsearch server:


require 'vendor/autoload.php';

use Elasticsearch\ClientBuilder;

$hosts = [

$client = ClientBuilder::create()

$params = [
    'index' => 'myindexname',
    'body' => [
        'query' => [
            'match' => [
                'post_title' => 'elasticsearch'

$response = $client->search($params);

$totalhits = $response['hits']['total'];
echo "We have $totalhits total hits\n";

echo "<P>The hits are the following:</P>";
$result = null;
while ($i <= $totalhits)
        $result[$i] = $response['hits']['hits'][$i]['_source'];

foreach ($result as $key => $value)
        echo $value['post_title'], "<br>";


Output will look something like this:

We have 2 total hits

The hits are the following:

Using Elasticsearch for JBOSS Logs
Deleting Entries in Elasticsearch Based On Timestamp

Update Nov/2019: Since Elasticsearch updated their basic license to include basic username/password security, it’s advisable to set them up. It’s a straight-forward addition:

$hosts = [
      'host' => 'myelasticsearchhost',
      'port' => '9200',
      'scheme' => 'http',
      'user' => 'myElasticUser',
      'pass' => 'myPassword'

Edit November 6, 2020: If there’s an upgrade or re-install of the OS into the latest version (such as from Ubuntu 16.x to 18.x), it is possible the version of cURL installed for PHP is a different one. For example, running php -m reveals:

PHP 7.2.34-8+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Oct 31 2020 16:57:15) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.34-8+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies

Since it is version 7.2 of PHP, install the cURL PHP library: apt-get install php7.2-curl