Skip to content
ZILLEALI edited this page Jun 19, 2026 · 1 revision

API Reference

Every public property and method on RouterosAPI, documented from the current source in routeros_api.class.php.

Properties

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)

Connection methods

connect($ip, $login, $password)

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/password login 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.

disconnect()

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.

Low level I/O methods

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.

write($command, $param2 = true)

Sends one or more API words to the router.

  • $command is 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.
  • $param2 controls 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=N word and terminate. Tags let you correlate asynchronous replies to a specific request when you have multiple outstanding commands, most scripts using comm() never need this directly

Returns false if $command is empty, true otherwise.

read($parse = true)

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 through parseResponse() before returning
  • $parse = false: returns the raw array of words exactly as received, useful if you want to inspect !re, !trap, !done markers yourself

comm($com, $arr = array())

The method most scripts actually call. It is a convenience wrapper around write() and read():

  1. Sends the command word ($com)
  2. 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
  3. Sends the final word, marking it as the last one
  4. Calls read() and returns the parsed result
$result = $API->comm('/ip/dhcp-server/lease/print', array(
    'count-only'      => '',
    '~active-address' => '1.1.',
));

Response parsing methods

parseResponse($response)

Takes the raw array of words from read(false) and turns it into a usable PHP structure:

  • Each !re marker starts a new row
  • Each key=value word inside a row sets $row['key'] = 'value'
  • !trap and !fatal rows are captured under those literal keys, so error responses do not silently disappear, check for a trap key in your result if a command that should return data comes back empty
  • If the response contains a single bare ret value and no !re rows 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.

parseResponse4Smarty($response)

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().

arrayChangeKeyName(&$array)

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.

Internal / protocol helpers

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.

encodeLength($length)

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

isIterable($var)

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.

debug($text)

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