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();
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);
$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
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
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.