PHP code example of php-opcua / opcua-client

1. Go to this page and download the library: Download php-opcua/opcua-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

php-opcua / opcua-client example snippets


use PhpOpcua\Client\ClientBuilder;
use PhpOpcua\Client\Types\NodeId;

$client = ClientBuilder::create()
    ->connect('opc.tcp://localhost:4840');

// Read server status — string format
$status = $client->read('i=2259');
echo $status->getValue(); // 0 = Running

// NodeId objects work too
$status = $client->read(NodeId::numeric(0, 2259));

$client->disconnect();

$refs = $client->browse('i=85'); // Objects folder

foreach ($refs as $ref) {
    echo "{$ref->displayName} ({$ref->nodeId})\n";
    //=> Server (ns=0;i=2253)
    //=> MyPLC (ns=2;i=1000)
}

$results = $client->readMulti()
    ->node('i=2259')->value()
    ->node('ns=2;i=1001')->displayName()
    ->node('ns=2;s=Temperature')->value()
    ->execute();

foreach ($results as $dataValue) {
    echo $dataValue->getValue() . "\n";
}

// All at once
$info = $client->getServerBuildInfo();
echo $info->productName;        // e.g. "UA-.NETStandard"
echo $info->manufacturerName;   // e.g. "OPC Foundation"
echo $info->softwareVersion;    // e.g. "1.5.374.126"

// Or individual fields
$client->getServerProductName();        // ?string
$client->getServerSoftwareVersion();    // ?string
$client->getServerBuildDate();          // ?DateTimeImmutable

$nodeId = $client->resolveNodeId('/Objects/MyPLC/Temperature');
$value = $client->read($nodeId);

echo $value->getValue();        // 23.5
echo $value->statusCode;        // 0 (Good)
echo $value->sourceTimestamp;    // DateTimeImmutable

use PhpOpcua\Client\Types\BuiltinType;

// Auto-detect type (reads the node first, caches the type)
$client->write('ns=2;i=1001', 42);

// Explicit type (validated against the node when auto-detect is on)
$client->write('ns=2;i=1001', 42, BuiltinType::Int32);

use PhpOpcua\Client\Types\Variant;

$result = $client->call(
    'i=2253',   // Server object
    'i=11492',  // GetMonitoredItems
    [new Variant(BuiltinType::UInt32, 1)],
);

echo $result->statusCode;                   // 0
echo $result->outputArguments[0]->value;    // [1001, 1002, ...]

$sub = $client->createSubscription(publishingInterval: 500.0);

$client->createMonitoredItems($sub->subscriptionId, [
    ['nodeId' => NodeId::numeric(2, 1001)],
]);

$response = $client->publish();
foreach ($response->notifications as $notif) {
    echo $notif->dataValue->getValue() . "\n";
}

$values = $client->historyReadRaw(
    'ns=2;i=1001',
    startTime: new DateTimeImmutable('-1 hour'),
    endTime: new DateTimeImmutable(),
);

foreach ($values as $dv) {
    echo "[{$dv->sourceTimestamp->format('H:i:s')}] {$dv->getValue()}\n";
}

use PhpOpcua\Client\Types\NodeClass;
use PhpOpcua\Client\Types\QualifiedName;
use PhpOpcua\Client\Types\StatusCode;

// Add a variable node
$results = $client->addNodes([
    [
        'parentNodeId'       => 'i=85',                              // Objects folder
        'referenceTypeId'    => 'i=35',                              // Organizes
        'requestedNewNodeId' => 'ns=2;s=MyVariable',
        'browseName'         => new QualifiedName(2, 'MyVariable'),
        'nodeClass'          => NodeClass::Variable,
        'typeDefinition'     => 'i=63',                              // BaseDataVariableType
    ],
]);

echo StatusCode::getName($results[0]->statusCode); // Good
echo $results[0]->addedNodeId;                     // ns=2;s=MyVariable

// Clean up when done
$client->deleteNodes([['nodeId' => 'ns=2;s=MyVariable']]);

use PhpOpcua\Client\ClientBuilder;
use PhpOpcua\Client\Security\SecurityPolicy;
use PhpOpcua\Client\Security\SecurityMode;

$client = ClientBuilder::create()
    ->setSecurityPolicy(SecurityPolicy::Basic256Sha256)
    ->setSecurityMode(SecurityMode::SignAndEncrypt)
    ->setClientCertificate('/certs/client.pem', '/certs/client.key', '/certs/ca.pem')
    ->setUserCredentials('operator', 'secret')
    ->connect('opc.tcp://192.168.1.100:4840');

use PhpOpcua\Client\ClientBuilder;
use PhpOpcua\Client\Repository\ExtensionObjectRepository;

$repo = new ExtensionObjectRepository();
$repo->register(NodeId::numeric(2, 5001), MyPointCodec::class);

$client = ClientBuilder::create($repo)
    ->connect('opc.tcp://localhost:4840');

$point = $client->read($pointNodeId)->getValue();
// ['x' => 1.5, 'y' => 2.5, 'z' => 3.5]

use PhpOpcua\Client\Testing\MockClient;
use PhpOpcua\Client\Types\DataValue;

$client = MockClient::create();

// Register a handler for read operations
$client->onRead(function (NodeId $nodeId) {
    return DataValue::ofDouble(23.5);
});

// Use the same API as a real client
$value = $client->read('ns=2;s=Temperature');
echo $value->getValue(); // 23.5

// Verify what was called
echo $client->callCount('read'); // 1

use PhpOpcua\Client\ClientBuilder;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('opcua');
$logger->pushHandler(new StreamHandler('php://stderr', Logger::DEBUG));

$client = ClientBuilder::create()
    ->setLogger($logger)
    ->connect('opc.tcp://localhost:4840');
// Logs: handshake, secure channel, session creation, reads, retries, errors...

use PhpOpcua\Client\ClientBuilder;
use PhpOpcua\Client\Event\DataChangeReceived;
use PhpOpcua\Client\Event\AlarmActivated;

// Set any PSR-14 event dispatcher on the builder
$client = ClientBuilder::create()
    ->setEventDispatcher($yourDispatcher)
    ->connect('opc.tcp://localhost:4840');

// In your listener:
class HandleDataChange {
    public function __invoke(DataChangeReceived $event): void {
        echo "Node changed on subscription {$event->subscriptionId}: "
            . $event->dataValue->getValue() . "\n";
    }
}

use PhpOpcua\Client\Event\AlarmActivated;
use PhpOpcua\Client\Event\AlarmSeverityChanged;

// Listen for alarm activation
class AlarmHandler {
    public function handleActivated(AlarmActivated $event): void {
        Log::critical("Alarm active: {$event->sourceName} (severity: {$event->severity})");
    }

    public function handleSeverity(AlarmSeverityChanged $event): void {
        if ($event->severity >= 800) {
            Notification::send($operators, new HighSeverityAlarm($event));
        }
    }
}

use PhpOpcua\Client\ClientBuilder;
use PhpOpcua\Client\TrustStore\FileTrustStore;
use PhpOpcua\Client\TrustStore\TrustPolicy;

$client = ClientBuilder::create()
    ->setTrustStore(new FileTrustStore())           // ~/.opcua/trusted/
    ->setTrustPolicy(TrustPolicy::Fingerprint)      // or FingerprintAndExpiry, Full
    ->connect('opc.tcp://192.168.1.100:4840');       // throws UntrustedCertificateException if not trusted

$builder = ClientBuilder::create()
    ->setTrustStore(new FileTrustStore())
    ->autoAccept(true);                    // accept new certificates
    // ->autoAccept(true, force: true);    // also accept changed certificates
$client = $builder->connect('opc.tcp://192.168.1.100:4840');

$client = ClientBuilder::create()
    ->setTrustPolicy(null)                // no trust policy
    ->connect('opc.tcp://192.168.1.100:4840');

$client = ClientBuilder::create()
    ->connect('opc.tcp://localhost:4840');
$client->discoverDataTypes();

$point = $client->read($pointNodeId)->getValue();
// ['x' => 1.5, 'y' => 2.5, 'z' => 3.5] — no codec needed

use PhpOpcua\Client\ClientBuilder;
use PhpOpcua\Client\Module\ReadWrite\ReadWriteModule;

// Add a custom module
$client = ClientBuilder::create()
    ->addModule(new MyQueryServiceModule())
    ->connect('opc.tcp://localhost:4840');

$client->queryFirst(...); // custom method from your module

// Replace a built-in module
$client = ClientBuilder::create()
    ->replaceModule(ReadWriteModule::class, new MyCustomReadWriteModule())
    ->connect('opc.tcp://localhost:4840');

$client->read(...); // uses your custom implementation

// Introspection
$client->hasMethod('read');                 // true
$client->hasModule(ReadWriteModule::class); // true

use PhpOpcua\Client\ClientBuilder;
use PhpOpcua\Nodeset\Robotics\RoboticsRegistrar;
use PhpOpcua\Nodeset\Robotics\RoboticsNodeIds;
use PhpOpcua\Nodeset\Robotics\Enums\OperationalModeEnumeration;

$client = ClientBuilder::create()
    ->loadGeneratedTypes(new RoboticsRegistrar())  // loads DI + IA dependencies automatically
    ->connect('opc.tcp://192.168.1.100:4840');

// Enum values are auto-cast to PHP BackedEnum
$mode = $client->read(RoboticsNodeIds::OperationalMode)->getValue();
// OperationalModeEnumeration::MANUAL_REDUCED_SPEED (not int 1)

// Structured types return typed DTOs with property access
$data = $client->read(RoboticsNodeIds::SomeStructuredNode)->getValue();
$data->Manufacturer;   // string — IDE autocomplete works
$data->Status;         // OperatingStateEnum — not a raw int
bash
composer 
bash
composer