-
Notifications
You must be signed in to change notification settings - Fork 273
API Reference
Every public property and method on RouterosAPI, documented from the current source in routeros_api.class.php.
| Property | Default | Purpose |
|---|---|---|
$debug |
false |
When true, echoes every command word sent and every byte length read, for troubleshooting the wire protocol itself |
$connected |
false |
Set internally once connect() succeeds, read it if you want to check connection state without storing your own flag |
$port |
8728 |
TCP port to connect to. Set to 8729 (or whatever you configured on the router) before calling connect() if using API-SSL |
$ssl |
false |
Set true to connect over api-ssl instead of plain API. See SSL and TLS Connections
|
$certless |
false |
Set true to allow SSL with no certificate verification, sets SECLEVEL=0 on the cipher string. Needed on OpenSSL 1.1+ for anonymous Diffie-Hellman. See SSL and TLS Connections
|
$timeout |
3 |
Seconds to wait per connection attempt and per data read before giving up |
$attempts |
5 |
Number of times connect() will retry before returning false
|
$delay |
3 |
Seconds to sleep between failed connection attempts |
$socket |
n/a | The underlying PHP stream resource. You generally do not touch this directly |
$error_no / $error_str
|
n/a | Populated by stream_socket_client() if the underlying TCP connection itself fails (separate from a RouterOS login failure) |
Opens the connection and logs in. Returns true on success, false if every attempt (up to $attempts) fails.
Internally this handles two different RouterOS login flows automatically:
- Pre-v6.43: RouterOS sends back an MD5 challenge, the class hashes the password against it and sends a second login request
-
v6.43 and later: RouterOS accepts a plain
name/passwordlogin in a single round trip
You do not need to know which version your router runs, connect() detects this from the shape of the first response and reacts accordingly.
Closes the socket if it is still a valid resource, and sets $connected = false. Safe to call even if the connection already dropped, it checks is_resource() first rather than assuming the socket is open.
This also runs automatically from __destruct(), so a script that ends or unsets $API without calling disconnect() explicitly will not leak an open socket, but calling it yourself is still good practice, particularly in long running daemons or loops that open many connections.
These are what comm() is built on top of. Use them directly only when you need finer control than comm() gives you, for example streaming a long running command like /tool/sniffer where you want to read results as they arrive rather than waiting for a single batch.
Sends one or more API words to the router.
-
$commandis a string. If it contains newlines, each line is sent as a separate word, this lets you pass a multi-line command block in one call. -
$param2controls what happens after the command is sent:-
true(default): send the command and terminate the sentence (the router will start processing it) -
false: send the command but do not terminate, use this when you have more parameter words to send first - an integer: send a
.tag=Nword and terminate. Tags let you correlate asynchronous replies to a specific request when you have multiple outstanding commands, most scripts usingcomm()never need this directly
-
Returns false if $command is empty, true otherwise.
Reads from the socket until RouterOS signals it is done (!done) and there are no unread bytes left, or the read times out. RouterOS responses are length-prefixed binary words; read() decodes the variable length encoding itself, you never deal with raw bytes.
-
$parse = true(default): runs the raw response throughparseResponse()before returning -
$parse = false: returns the raw array of words exactly as received, useful if you want to inspect!re,!trap,!donemarkers yourself
The method most scripts actually call. It is a convenience wrapper around write() and read():
- Sends the command word (
$com) - Iterates
$arr, builds a properly prefixed word for each entry based on the first character of the key, see Writing Queries for the full rules on=,?, and~prefixes - Sends the final word, marking it as the last one
- Calls
read()and returns the parsed result
$result = $API->comm('/ip/dhcp-server/lease/print', array(
'count-only' => '',
'~active-address' => '1.1.',
));Takes the raw array of words from read(false) and turns it into a usable PHP structure:
- Each
!remarker starts a new row - Each
key=valueword inside a row sets$row['key'] = 'value' -
!trapand!fatalrows are captured under those literal keys, so error responses do not silently disappear, check for atrapkey in your result if a command that should return data comes back empty - If the response contains a single bare
retvalue and no!rerows at all (some commands return one scalar instead of a row set),parseResponse()returns that scalar directly rather than an empty array
This is also what comm() calls internally, you only need to call it yourself if you used read(false) directly.
A variant of parseResponse() intended for feeding data into a Smarty template, where hyphenated RouterOS property names like mac-address are awkward to reference. It runs the same parsing logic, then passes every row through arrayChangeKeyName() to convert - and / to _.
Known quirk: in the current source, the return $PARSED; statement executes before the trailing if (empty($PARSED) && !is_null($singlevalue)) check, which means that fallback branch is unreachable dead code. In practice this means parseResponse4Smarty() will never collapse down to a bare scalar the way parseResponse() does for single-value responses, it always returns an array, even if that array is empty. For most /print-style usage this does not matter, but it is worth knowing if you are debugging why a single-value command behaves differently through this method versus parseResponse().
Replaces - and / in every key of $array with _. Used internally by parseResponse4Smarty(), but you can call it yourself on any row if you prefer underscore-style keys:
$row = $API->arrayChangeKeyName($interfaces[0]);
echo $row['mac_address']; // instead of $interfaces[0]['mac-address']Edge case: if you pass an empty array, the internal $array_new variable is never assigned inside the foreach loop (because the loop body never runs), and the method returns an undefined variable. On PHP 8 this raises a warning rather than a fatal error and effectively returns null. Guard against empty arrays before calling this if you are on PHP 8 with strict error reporting.
You will rarely call these directly, but they are documented here since they are public methods and understanding them helps when debugging at the wire protocol level.
Encodes an integer length into RouterOS's variable length binary prefix format, the same scheme the API protocol uses for every word it sends. The encoding uses 1 to 5 bytes depending on size:
| Length range | Bytes used |
|---|---|
< 0x80 |
1 |
< 0x4000 |
2 |
< 0x200000 |
3 |
< 0x10000000 |
4 |
>= 0x10000000 |
5 |
Returns true if $var is a non-null array, Traversable, Iterator, or IteratorAggregate. Used by comm() to guard the parameter loop so passing a non-iterable second argument does not throw a fatal error, it just skips sending any parameters.
Echoes $text followed by a newline, only if $this->debug is true. Every other method calls this internally rather than echoing directly, so toggling the single $debug property controls all diagnostic output across the class.
Documentation contributed by Zill E Ali, Network Engineer and creator of mikrotik-laravel | GitHub | LinkedIn
Documentation maintained by Zill E Ali Network Engineer, MikroTik RouterOS / ISP infrastructure specialist, MTCNA Certified
- GitHub: github.com/Zilleali
- Website: zilleali.com
- LinkedIn: linkedin.com/in/zilleali12
Found an error or have something to add? Open a PR against this wiki or reach out directly.