PHPackages                             cjtaylor-adepteo/xmpp-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. cjtaylor-adepteo/xmpp-php

ActivePackage[API Development](/categories/api)

cjtaylor-adepteo/xmpp-php
=========================

PHP library for XMPP.

v3.0.1(2y ago)0104MITPHPPHP &gt;=8.1

Since Dec 14Pushed 2y agoCompare

[ Source](https://github.com/cjtaylor-adepteo/xmpp-php)[ Packagist](https://packagist.org/packages/cjtaylor-adepteo/xmpp-php)[ RSS](/packages/cjtaylor-adepteo-xmpp-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (27)Used By (0)

PHP client library for XMPP (Jabber) protocol
=============================================

[](#php-client-library-for-xmpp-jabber-protocol)

[![Latest Stable Version](https://camo.githubusercontent.com/6a34ceafee313d83be603d279905eb36cb028f23fe802fa63567d2ba05da8a22/68747470733a2f2f706f7365722e707567782e6f72672f6e6f7267756c2f786d70702d7068702f762f737461626c65)](https://packagist.org/packages/norgul/xmpp-php)[![Total Downloads](https://camo.githubusercontent.com/d3e82432ec5251b273fde085fea3fbc27d361db59529212d4bdb02e5521c9762/68747470733a2f2f706f7365722e707567782e6f72672f6e6f7267756c2f786d70702d7068702f646f776e6c6f616473)](https://packagist.org/packages/norgul/xmpp-php)[![Latest Unstable Version](https://camo.githubusercontent.com/0e568d0bbae8fa2cfe97e47aa80c63c5f1a5734ee79ccce35c8112341adcb6c3/68747470733a2f2f706f7365722e707567782e6f72672f6e6f7267756c2f786d70702d7068702f762f756e737461626c65)](https://packagist.org/packages/norgul/xmpp-php)[![Build Status](https://camo.githubusercontent.com/efd6fa701663b080faa38e37ac415977fb3cb2a8992072b427f106eec79122c3/68747470733a2f2f7472617669732d63692e6f72672f4e6f7267756c2f786d70702d7068702e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/Norgul/xmpp-php)[![License](https://camo.githubusercontent.com/780d56d57d38900d3b8c0e376087e763d2c026ddd2d07a693c17d8fb91d6afbd/68747470733a2f2f706f7365722e707567782e6f72672f6e6f7267756c2f786d70702d7068702f6c6963656e7365)](https://packagist.org/packages/norgul/xmpp-php)

This is low level socket implementation for enabling PHP to communicate with XMPP due to lack of such libraries online (at least ones I could find that had decent documentation).

XMPP core documentation can be found [here](https://xmpp.org/rfcs/rfc6120.html).

Installation requirements and example
=====================================

[](#installation-requirements-and-example)

Project requirements are given in `composer.json` ( [Composer website](https://getcomposer.org)):

You can use this library in your project by running:

```
composer require norgul/xmpp-php

```

You can see usage example in `Example.php` file by changing credentials to point to your XMPP server and from project root run `php Example.php`.

Library usage
=============

[](#library-usage)

Initialization
--------------

[](#initialization)

In order to start using the library you first need to instantiate a new `Options`class. Host, username and password are mandatory fields, while port number, if omitted, will default to `5222` which is XMPP default.

Username can be either bare `JID` or in `JID/resource` form. If you are using a bare `JID`the resource will be added automatically. You can override this by explicitly setting a resource with `$client->iq->setResource()`. In the second case the username will be automatically parsed to `username` and `resource` variables. In case of `JID/resource/xyz` format, everything after second slash will be ignored. If both `JID/resource` is present as well as using the `$client->iq->setResource()` method, which ever was defined last will take precedence.

```
$options = new Options();

$options
    ->setHost($host)            // required
    ->setPort($port)            // not required, defaults to 5222
    ->setUsername($username)    // required
    ->setPassword($password);   // required

```

`Options` object is required for establishing the connection and every other subsequent request, so once set it should not be changed.

Once this is set you can instantiate a new `XmppClient` object and pass the `Options` object in.

XMPP client class explanation
-----------------------------

[](#xmpp-client-class-explanation)

Since XMPP is all about 3 major stanzas, (**IQ, Message and Presence**), I've created separate classes which are dependant on socket implementation so that you can directly send XML by calling a stanza method.

This means that 3 stanzas have been made available from `XmppClient` class constructor to be used like a chained method on client's concrete class.

Current logic thus is `$client->STANZA->METHOD()`. For example:

```
$client->iq->getRoster();
$client->message->send();
$client->presence->subscribe();

```

Connecting to the server
------------------------

[](#connecting-to-the-server)

Beside being a stanza wrapper, `XmppClient` class offers a few public methods.

`$client->connect()` method does a few things:

1. Connects to the socket which was initialized in `XmppClient` constructor
2. Opens an XML stream to exchange with the XMPP server
3. Tries to authenticate with the server based on provided credentials
4. Starts the initial communication with the server, bare minimum to get you started

Current version supports `PLAIN` and `DIGEST-MD5` auth methods.

TLS is supported by default. If server has support for TLS, library will automatically try to connect with TLS and make the connection secure.

If you'd like to explicitly disable this functionality, you can use `setUseTls(false)`function on the `Options` instance so that TLS communication is disabled. Note that this will function in environments where TLS is supported but not required. If TLS is required, program will connect to it independently of the option you set.

Sending raw data
----------------

[](#sending-raw-data)

`send()` message is exposed as being public in `XmppClient` class, and its intention is to send raw XML data to the server. For it to work correctly, XML which you send has to be valid XML.

Getting raw response
--------------------

[](#getting-raw-response)

Server responses (or server side continuous XML session to be exact) can be retrieved with `$client->getResponse()`. This should be used in an infinite loop or for more sustainable solution in some WebSocket solution like [Ratchet](http://socketo.me/) if you'd like to see continuous stream of everything coming from the server.

If you would like to see the output of the received response in the console you can call the `$client->prettyPrint($response)` method.

Receiving messages and other responses
--------------------------------------

[](#receiving-messages-and-other-responses)

In case you are not interested in complete response which comes from server, you may also use `$client->message->receive()` (`$client->getMessages()` was removed because it was just a shorthand method for this one) which will match message tags with regex and return array of matched messages. In case you'd like to see the response in the terminal, you can do something like this:

```
do {
    $response = $client->message->receive();
    if($response)
        echo print_r($response);
} while (true);

```

Disconnect
----------

[](#disconnect)

Disconnect method sends closing XML to the server to end the currently open session and closes the open socket.

Stanza method breakdown
=======================

[](#stanza-method-breakdown)

Remember from [here](#xmpp-client-class-explanation) -&gt; `$client->STANZA->METHOD()`

Message
-------

[](#message)

`send()` - sending a message to someone. Takes 3 parameters of which the last one is optional. First parameter is the actual message you'd like to send (body), second one is recipient of the message and third one is type of message to be sent. This defaults to `chat`.

You can find possible types in [this RFC document](https://xmpp.org/rfcs/rfc3921.html#stanzas)

`receive()` - covered in [this section](#receiving-messages-and-other-responses)

IQ
--

[](#iq)

`getRoster()` - takes no arguments and fetches current authenticated user roster.

`setGroup()` - puts a given user in group you provide. Method takes two arguments: first one being the group name which you will attach to given user, and other being JID of that user.

Presence
--------

[](#presence)

`setPriority()` - sets priority for given resource. First argument is an integer `-128  127`. If no second argument is given, priority will be set for currently used resource. Other resource can be provided as a second argument whereas the priority will be set for that specific resource.

`subscribe()` - takes JID as an argument and asks that user for presence.

`acceptSubscription()` - takes JID as an argument and accepts presence from that user.

`declineSubscription()` - takes JID as an argument and declines presence from that user.

Sessions
--------

[](#sessions)

Sessions are currently being used only to differentiate logs if multiple connections are being made.

`XmppClient` class takes in second optional parameter `$sessionId` to which you can forward session ID from your system, or it will be assigned automatically.

You can disable sessions through `Options` object (`$options->setSessionManager(false)`), as they can cause collision with already established sessions if being used inside frameworks or similar. Needless to say if this is disabled, forwarding a second parameter to `XmppClient` will not establish a new session.

More options (not required)
===========================

[](#more-options-not-required)

`Options` object can take more options which may be chained but are not required. These are explained and commented in the code directly in the `Options` class:

```
$options
    ->setProtocol($protocol)  // defaults to TCP
    ->setResource($resource)  // defaults to 'norgul_machine_' string + timestamp
    ->setLogger($logger)      // logger instance (logging explained below)
    ->setAuthType($authType)  // Takes on classes which implement Authenticable

```

Socket options
--------------

[](#socket-options)

Most of the socket options are set by default so there is no need to tamper with this class, however you can additionally change the timeout for the period the socket will be alive when doing a `socket_read()`, and you can do that with `$socket->setTimeout()`.

Logging
-------

[](#logging)

Upon new established session the library is creating a `xmpp.log` log file in `logs/` folder:

You can manually set logger when instantiating `Options` with `setLogger($logger)`. The method accepts any object which implements `Loggable` interface so you can create your own implementation.

Fun fact: this used to be a `PSR-3` logger interface, but I decided it was an overkill for this stage of development.

Other
=====

[](#other)

`Example.php` has a `sendRawXML()` method which can be helpful with debugging. Method works in a way that you can provide hand-written XML and send it to the server. On the other hand you can also trigger a method by providing method name instead of XML.

```
Enter XML: foo
