PHP code example of suthernfriend / mikrotik-api

1. Go to this page and download the library: Download suthernfriend/mikrotik-api 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/ */

    

suthernfriend / mikrotik-api example snippets



use MikroTikApi\ConnectionManager;
use Psr\Log\LoggerInterface;

/** @var LoggerInterface $logger */
$logger = getPsrLoggerInterface();

/** @var array $config */
$config = [
    "router1" => [
        "host" => "10.1.1.1",
        "user" => "admin",
        "password" => "passwordForRouter1",
    ],
    "router2" => [
        "host" => "10.1.2.1",
        "user" => "admin",
        "password" => "passwordForRouter2",
    ]
];

$connectionManager = new ConnectionManager($logger, $config);



namespace App;

use MikroTikApi\ConnectionManager;
use MikroTikApi\DataObjectArray;
use MikroTikApi\DataObject;

/** @var ConnectionManager $connectionManager */
$connectionManager = new ConnectionManager($logger, $config);

// Read something
/** @var DataObjectArray $obj */
$obj = $connectionManager->createRequest("router1")->ip->address->print();

echo "$obj\n";
/**
 * Will print p.e. 
 * [
 *   { id: *27, address: 10.1.1.1/24, network: 10.1.1.0, interface: eth1, actualInterface: eth1, dynamic: false, invalid: false, disabled: false },
 *   { id: *2A, address: 192.168.1.1/24, network: 192.168.1.0, interface: trunk, actualInterface: trunk, dynamic: false, invalid: false, disabled: false }
 * ]
 */

// Add an object
$vlanInterface = DataObject::create([
	"name" => "myVlanInterface",
	"vlanId" => 50,
	"interface" => "trunk"
]);

$connectionManager->createRequest("router1")->interface->vlan->add($vlanInterface);

// Change an object
$query = DataObject::create([ "address" => "192.168.1.100" ]);

$lease = $connectionManager->createRequest("router1")->ip->dhcpServer->lease->print($query);
$lease->address = "192.168.1.101";

$connectionManager->createRequest("router1")->ip->dhcpServer->lease->set($lease);

// Use some other action
// without argument createRequest() will use the first ! router given by $config
$connectionManager->createRequest()->ip->dhcpServer->lease->makeStatic($lease);




$prov = $connectionManager->createRequest()->capsMan->provisioning->print(\MikroTikApi\DataObject::create(["comment" => "first-config"]))->getOne();
echo $prov->radioMac . "\n";
echo $prov->commonNameRegexp . "\n";


$prov = $connectionManager->createRequest()->capsMan->provisioning->print(\MikroTikApi\DataObject::create(["comment" => "first-config"]))->getOne();
$prov->action = "create-dynamic-enabled";