Community discussions

MikroTik App
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

PHP + Mikrotik 5.12

Mon Jan 23, 2012 12:26 am

Hi everyone,

This is my first post in this great forum, hoping to solve some problems that I have with the Mikrotik PHP API.

Well, first of all I downloaded the last Mikrotik release and installed it into a VirtualBox machine. All I want is to connect Mikrotik to a PHP interface so I can extract some interesting information. So I put this file, called routeros_api.class.php in a web server:
<?php
/*****************************
 *
 * RouterOS PHP API class v1.4
 * Author: Denis Basta
 * Contributors:
 *    Nick Barnes
 *    Ben Menking (ben [at] infotechsc [dot] com)
 *    Jeremy Jefferson (http://jeremyj.com)
 *    Cristian Deluxe (djcristiandeluxe [at] gmail [dot] com)
 *
 * http://www.mikrotik.com
 * http://wiki.mikrotik.com/wiki/API_PHP_class
 *
 ******************************/

class routeros_api
{
    var $debug = false;      // Show debug information
    var $error_no;           // Variable for storing connection error number, if any
    var $error_str;          // Variable for storing connection error text, if any
    var $attempts = 5;       // Connection attempt count
    var $connected = false;  // Connection state
    var $delay = 3;          // Delay between connection attempts in seconds
    var $port = 8728;        // Port to connect to
    var $timeout = 3;        // Connection attempt timeout and data read timeout
    var $socket;             // Variable for storing socket resource
    
    /**
     * Print text for debug purposes
     *
     * @param string      $text       Text to print
     *
     * @return void
     */
    function debug($text)
    {
        if ($this->debug)
            echo $text . "\n";
    }
	
	
    /**
     * 
     *
     * @param string        $length
     *
     * @return void
     */
    function encode_length($length)
    {
        if ($length < 0x80) {
            $length = chr($length);
        } else if ($length < 0x4000) {
            $length |= 0x8000;
            $length = chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
        } else if ($length < 0x200000) {
            $length |= 0xC00000;
            $length = chr(($length >> 16) & 0xFF) . chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
        } else if ($length < 0x10000000) {
            $length |= 0xE0000000;
            $length = chr(($length >> 24) & 0xFF) . chr(($length >> 16) & 0xFF) . chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
        } else if ($length >= 0x10000000)
            $length = chr(0xF0) . chr(($length >> 24) & 0xFF) . chr(($length >> 16) & 0xFF) . chr(($length >> 8) & 0xFF) . chr($length & 0xFF);
        return $length;
    }
	
	
    /**
     * Login to RouterOS
     *
     * @param string      $ip         Hostname (IP or domain) of the RouterOS server
     * @param string      $login      The RouterOS username
     * @param string      $password   The RouterOS password
     *
     * @return boolean                If we are connected or not
     */
    function connect($ip, $login, $password)
    {
        for ($ATTEMPT = 1; $ATTEMPT <= $this->attempts; $ATTEMPT++) {
            $this->connected = false;
            $this->debug('Connection attempt #' . $ATTEMPT . ' to ' . $ip . ':' . $this->port . '...');
            if ($this->socket = @fsockopen($ip, $this->port, $this->error_no, $this->error_str, $this->timeout)) {
                socket_set_timeout($this->socket, $this->timeout);
                $this->write('/login');
                $RESPONSE = $this->read(false);
                if ($RESPONSE[0] == '!done') {
                    if (preg_match_all('/[^=]+/i', $RESPONSE[1], $MATCHES)) {
                        if ($MATCHES[0][0] == 'ret' && strlen($MATCHES[0][1]) == 32) {
                            $this->write('/login', false);
                            $this->write('=name=' . $login, false);
                            $this->write('=response=00' . md5(chr(0) . $password . pack('H*', $MATCHES[0][1])));
                            $RESPONSE = $this->read(false);
                            if ($RESPONSE[0] == '!done') {
                                $this->connected = true;
                                break;
                            }
                        }
                    }
                }
                fclose($this->socket);
            }
            sleep($this->delay);
        }
        if ($this->connected)
            $this->debug('Connected...');
        else
            $this->debug('Error...');
        return $this->connected;
    }
	
	
    /**
     * Disconnect from RouterOS
     *
     * @return void
     */
    function disconnect()
    {
        fclose($this->socket);
        $this->connected = false;
        $this->debug('Disconnected...');
    }
	
	
    /**
     * Parse response from Router OS
     *
     * @param array       $response   Response data
     *
     * @return array                  Array with parsed data
     */
    function parse_response($response)
    {
        if (is_array($response)) {
            $PARSED      = array();
            $CURRENT     = null;
            $singlevalue = null;
            $count       = 0;
            foreach ($response as $x) {
                if (in_array($x, array(
                    '!fatal',
                    '!re',
                    '!trap'
                ))) {
                    if ($x == '!re') {
                        $CURRENT =& $PARSED[];
                    } else
                        $CURRENT =& $PARSED[$x][];
                } else if ($x != '!done') {
                    if (preg_match_all('/[^=]+/i', $x, $MATCHES)) {
                        if ($MATCHES[0][0] == 'ret') {
                            $singlevalue = $MATCHES[0][1];
                        }
						$CURRENT[$MATCHES[0][0]] = (isset($MATCHES[0][1]) ? $MATCHES[0][1] : '');
					}
                }
            }
            if (empty($PARSED) && !is_null($singlevalue)) {
                $PARSED = $singlevalue;
            }
            return $PARSED;
        } else
            return array();
    }
	
	
    /**
     * Parse response from Router OS
     *
     * @param array       $response   Response data
     *
     * @return array                  Array with parsed data
     */
    function parse_response4smarty($response)
    {
        if (is_array($response)) {
            $PARSED  = array();
            $CURRENT = null;
            $singlevalue = null;
            foreach ($response as $x) {
                if (in_array($x, array(
                    '!fatal',
                    '!re',
                    '!trap'
                ))) {
                    if ($x == '!re')
                        $CURRENT =& $PARSED[];
                    else
                        $CURRENT =& $PARSED[$x][];
                } else if ($x != '!done') {
                    if (preg_match_all('/[^=]+/i', $x, $MATCHES)) {
                        if ($MATCHES[0][0] == 'ret') {
                            $singlevalue = $MATCHES[0][1];
                        }
                        $CURRENT[$MATCHES[0][0]] = (isset($MATCHES[0][1]) ? $MATCHES[0][1] : '');
					}
                }
            }
            foreach ($PARSED as $key => $value) {
                $PARSED[$key] = $this->array_change_key_name($value);
            }
            return $PARSED;
            if (empty($PARSED) && !is_null($singlevalue)) {
                $PARSED = $singlevalue;
            }
        } else {
            return array();
        }
    }
	
	
    /**
     * Change "-" and "/" from array key to "_"
     *
     * @param array       $array      Input array
     *
     * @return array                  Array with changed key names
     */
    function array_change_key_name(&$array)
    {
        if (is_array($array)) {
            foreach ($array as $k => $v) {
                $tmp = str_replace("-", "_", $k);
                $tmp = str_replace("/", "_", $tmp);
                if ($tmp) {
                    $array_new[$tmp] = $v;
                } else {
                    $array_new[$k] = $v;
                }
            }
            return $array_new;
        } else {
            return $array;
        }
    }
	
	
    /**
     * Read data from Router OS
     *
     * @param boolean     $parse      Parse the data? default: true
     *
     * @return array                  Array with parsed or unparsed data
     */
    function read($parse = true)
    {
        $RESPONSE = array();
        while (true) {
            // Read the first byte of input which gives us some or all of the length
            // of the remaining reply.
            $BYTE   = ord(fread($this->socket, 1));
            $LENGTH = 0;
            // If the first bit is set then we need to remove the first four bits, shift left 8
            // and then read another byte in.
            // We repeat this for the second and third bits.
            // If the fourth bit is set, we need to remove anything left in the first byte
            // and then read in yet another byte.
            if ($BYTE & 128) {
                if (($BYTE & 192) == 128) {
                    $LENGTH = (($BYTE & 63) << 8) + ord(fread($this->socket, 1));
                } else {
                    if (($BYTE & 224) == 192) {
                        $LENGTH = (($BYTE & 31) << 8) + ord(fread($this->socket, 1));
                        $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
                    } else {
                        if (($BYTE & 240) == 224) {
                            $LENGTH = (($BYTE & 15) << 8) + ord(fread($this->socket, 1));
                            $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
                            $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
                        } else {
                            $LENGTH = ord(fread($this->socket, 1));
                            $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
                            $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
                            $LENGTH = ($LENGTH << 8) + ord(fread($this->socket, 1));
                        }
                    }
                }
            } else {
                $LENGTH = $BYTE;
            }
            // If we have got more characters to read, read them in.
            if ($LENGTH > 0) {
                $_      = "";
                $retlen = 0;
                while ($retlen < $LENGTH) {
                    $toread = $LENGTH - $retlen;
                    $_ .= fread($this->socket, $toread);
                    $retlen = strlen($_);
                }
                $RESPONSE[] = $_;
                $this->debug('>>> [' . $retlen . '/' . $LENGTH . '] bytes read.');
            }
            // If we get a !done, make a note of it.
            if ($_ == "!done")
                $receiveddone = true;
            $STATUS = socket_get_status($this->socket);
            if ($LENGTH > 0)
                $this->debug('>>> [' . $LENGTH . ', ' . $STATUS['unread_bytes'] . ']' . $_);
            if ((!$this->connected && !$STATUS['unread_bytes']) || ($this->connected && !$STATUS['unread_bytes'] && $receiveddone))
                break;
        }
        if ($parse)
            $RESPONSE = $this->parse_response($RESPONSE);
        return $RESPONSE;
    }
	
	
    /**
     * Write (send) data to Router OS
     *
     * @param string      $command    A string with the command to send
     * @param mixed       $param2     If we set an integer, the command will send this data as a "tag"
     *                                If we set it to boolean true, the funcion will send the comand and finish
     *                                If we set it to boolean false, the funcion will send the comand and wait for next command
     *                                Default: true
     *
     * @return boolean                Return false if no command especified
     */
    function write($command, $param2 = true)
    {
        if ($command) {
            $data = explode("\n", $command);
            foreach ($data as $com) {
                $com = trim($com);
                fwrite($this->socket, $this->encode_length(strlen($com)) . $com);
                $this->debug('<<< [' . strlen($com) . '] ' . $com);
            }
            if (gettype($param2) == 'integer') {
                fwrite($this->socket, $this->encode_length(strlen('.tag=' . $param2)) . '.tag=' . $param2 . chr(0));
                $this->debug('<<< [' . strlen('.tag=' . $param2) . '] .tag=' . $param2);
            } else if (gettype($param2) == 'boolean')
                fwrite($this->socket, ($param2 ? chr(0) : ''));
            return true;
        } else
            return false;
    }
	
	
    /**
     * Write (send) data to Router OS
     *
     * @param string      $com        A string with the command to send
     * @param array       $arr        An array with arguments or queries
     *
     * @return array                  Array with parsed
     */
    function comm($com, $arr = array())
    {
        $count = count($arr);
        $this->write($com, !$arr);
        $i = 0;
        foreach ($arr as $k => $v) {
            switch ($k[0]) {
                case "?":
                    $el = "$k=$v";
                    break;
                case "~":
                    $el = "$k~$v";
                    break;
                default:
                    $el = "=$k=$v";
                    break;
            }
            $last = ($i++ == $count - 1);
            $this->write($el, $last);
        }
        return $this->read();
    }
}
?>
Later, I started a DHCP client in my Mikrotik machine, with the command:
ip dhcp-client add interface=ether1 disabled=no
And finally (this is where "it hurts"), I uploaded this file to my web server:
<?php

require('routeros_api.class.php');

$API = new routeros_api();

$API->debug = true;

if ($API->connect('192.168.1.135', 'admin', 'admin')) {

   $API->write('/interface/getall');

   $READ = $API->read(false);
   $ARRAY = $API->parse_response($READ);

   print_r($ARRAY);

   $API->disconnect();

}

?>
Nothing more to say, the example crashes and doesn't list anything. Moreover, it looks like there's no connection between my webserver and the machine. And they are in the same IP range (192.168.1.0/24).

Any ideas? Am I doing something wrong?

My english is not one of my bests, sorry. It would be great if anyone cuold help me.

Thanks in advance!
 
User avatar
nest
Forum Veteran
Forum Veteran
Posts: 823
Joined: Tue Feb 27, 2007 1:52 am
Location: UK
Contact:

Re: PHP + Mikrotik 5.12

Mon Jan 23, 2012 12:43 am

1. Can the web server ping the router ok? (proves the physical connection is ok)
2. Create a new php file with just:
<?php phpinfo(); ?>
- Does that work ok? (proves php is installed and working ok)
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

Re: PHP + Mikrotik 5.12

Mon Jan 23, 2012 11:45 am

Hi, thanks for your reply. Here are some screenshots so you can see what it does.

Ping from WebServer to Mikrotik:
Image

Mikrotik's IP:
Image

PHP:
Image

Error:
Image

Looks like my WebServer is doing well, what about Mikrotik? Should I open some ports or something?

Thanks nest!
 
dog
Member Candidate
Member Candidate
Posts: 186
Joined: Wed Aug 12, 2009 3:37 pm
Location: Germany

Re: PHP + Mikrotik 5.12

Mon Jan 23, 2012 12:08 pm

Check under IP > Services that api is actually enabled.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: PHP + Mikrotik 5.12

Mon Jan 23, 2012 5:54 pm

In addition to dog's suggestion, I'd like to invite you to try out the client from my signature. It's more intuitive to work with, I promise :D (I welcome your feedback either way).
 
User avatar
nest
Forum Veteran
Forum Veteran
Posts: 823
Joined: Tue Feb 27, 2007 1:52 am
Location: UK
Contact:

Re: PHP + Mikrotik 5.12

Mon Jan 23, 2012 9:54 pm

Check under IP > Services that api is actually enabled.
Good call as by default API service is disabled.
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

Re: PHP + Mikrotik 5.12

Mon Jan 23, 2012 11:04 pm

Check under IP > Services that api is actually enabled.
That was the problem man! Lots of thanks.

Just did:
ip service set numbers="api" address="0.0.0.0/0" disabled="no"
and everything worked like a charm.
In addition to dog's suggestion, I'd like to invite you to try out the client from my signature. It's more intuitive to work with, I promise :D (I welcome your feedback either way).
In fact, I have to do a little proyect and your client is very interesting. I'm working with it at the moment. Thanks! (It should appear in Mikrotik Wiki :D).
Check under IP > Services that api is actually enabled.
Good call as by default API service is disabled.
Thanks a lot anyway!
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: PHP + Mikrotik 5.12

Tue Jan 24, 2012 6:19 pm

In fact, I have to do a little proyect and your client is very interesting. I'm working with it at the moment. Thanks! (It should appear in Mikrotik Wiki :D).
It... is... :?

I mean, it's in the "API examples elsewhere" section, since it's hosted elsewhere. For some reason, clients hosted in the wiki have something "magical" about them that makes people ignore the "elsewhere" section (it's not just my client... the .NET client in the elsewhere section is awesome, and yet I keep seeing people with the wiki .NET client).

I plan to write up a Wiki entry with examples, but my problem is I miss some "real world" examples to fill the page with. Most stuff I can think of is either too complex, or too trivial to be called "real world".
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

Re: PHP + Mikrotik 5.12

Thu Jan 26, 2012 1:44 am

In fact, I have to do a little proyect and your client is very interesting. I'm working with it at the moment. Thanks! (It should appear in Mikrotik Wiki :D).
I plan to write up a Wiki entry with examples, but my problem is I miss some "real world" examples to fill the page with. Most stuff I can think of is either too complex, or too trivial to be called "real world".
As I said, I'm currently working on a little proyect. I could show it to you, but I should do some coding first. If you're interested just send me a private message. It's just another Mikrotik front-end, nothing special.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: PHP + Mikrotik 5.12

Thu Jan 26, 2012 3:22 pm

In fact, I have to do a little proyect and your client is very interesting. I'm working with it at the moment. Thanks! (It should appear in Mikrotik Wiki :D).
I plan to write up a Wiki entry with examples, but my problem is I miss some "real world" examples to fill the page with. Most stuff I can think of is either too complex, or too trivial to be called "real world".
As I said, I'm currently working on a little proyect. I could show it to you, but I should do some coding first. If you're interested just send me a private message. It's just another Mikrotik front-end, nothing special.
There are no PMs allowed in this forum for some odd reason.

I'm interested, yes. When you're ready, you could post it here, or perhaps at the Wiki or at Github.

BTW, I saw your karma message, and I guess you're right in that the installation seems harder. I've tried to reccomend Pyrus while still allowing for plain file extraction, but I guess that's futile... I should just give both options an equal "reccomendation" status. Or maybe you meant something to reduce even the file extraction bit?
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

Re: PHP + Mikrotik 5.12

Fri Jan 27, 2012 12:37 pm

There are no PMs allowed in this forum for some odd reason.

I'm interested, yes. When you're ready, you could post it here, or perhaps at the Wiki or at Github.

BTW, I saw your karma message, and I guess you're right in that the installation seems harder. I've tried to reccomend Pyrus while still allowing for plain file extraction, but I guess that's futile... I should just give both options an equal "reccomendation" status. Or maybe you meant something to reduce even the file extraction bit?
Well, I think the proyect has enough quality to be shown, you can check it out here. It's in Spanish, that's the only problem (should I translate it to English?), the webserver is an Ubuntu Server 11.10 machine with apache and vsftpd working under VirtualBox. The HTML5 design is based on this template. Nothing special.

Talking about Pyrus, I could manage to install your API in my local machine but I couldn't do it in my webserver. Just downloaded the source code and uploaded it into the '/var/www' directory.

I would like to receive any kind of idea or criticism, this is just a beta release.

EDIT: I forgot it! There's a MikroTik machine working behind all of this. It has a demo key. The credentials are:
  • IP: 192.168.1.132
  • login: admin
  • password: admin
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: PHP + Mikrotik 5.12

Fri Jan 27, 2012 5:40 pm

Well, I think the proyect has enough quality to be shown, you can check it out here. It's in Spanish, that's the only problem (should I translate it to English?), the webserver is an Ubuntu Server 11.10 machine with apache and vsftpd working under VirtualBox. The HTML5 design is based on this template. Nothing special.
If you want non-Spanish speaking people to use it, then an English translation is basically a must.
Talking about Pyrus, I could manage to install your API in my local machine but I couldn't do it in my webserver.
How come? What did you do differently? I mean, a simple
php pyrus.phar
from the server's command line should've been sufficient for Pyrus installation. And then adding "<your-pear-dir>/php" to your include_path to actually be able to include the packages.
Just downloaded the source code and uploaded it into the '/var/www' directory.
Yes, that's a completely valid method of installation, hence the earlier point about me promoting Pyrus being a futile attempt.
I would like to receive any kind of idea or criticism, this is just a beta release.
Add queues and address lists, and you've basically covered everything I use at my network. If instead you intend for this panel to be "end user friendly", then perhaps the only thing you should add is a "mac clone" option.
Last edited by boen_robot on Fri Jan 27, 2012 7:24 pm, edited 1 time in total.
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

Re: PHP + Mikrotik 5.12

Fri Jan 27, 2012 5:45 pm

Maybe someone could help me.

I'm having some problems to remove a DHCP network:
// Si todo va bien mostramos un mensaje.
if ($cliente->sendSync($peticionRed)->getType() !== Response::TYPE_FINAL) {
        // Si no, borramos la red DHCP.
        $peticionRed = new Request('/ip dhcp-server network remove');
        // Entiendo que solo puede haber un DHCP dando gateway y DNS.
        $peticionRed->setArgument("numbers", "0");
        $cliente->sendSync($peticionRed);

        echo "<p>Red DHCP por defecto eliminada con &eacute;xito.</p>";
        } else {
                  echo "<p>Red DHCP por defecto creada con &eacute;xito.</p>";
        }
}
It just doesn't work. It properly shows the message "Red DHCP por defecto eliminada con éxito." but the DHCP network is still there.

Am I doing something wrong?
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

Re: PHP + Mikrotik 5.12

Fri Jan 27, 2012 5:52 pm

Add queues and address lists, and you've basically covered everything I use at my network. If instead you intend for this panel to be "end user friendly", then perhaps the only thing you should add is a "mac clone" option.
Thank you very much for all of your help!

Mac clone option? Please tell me a bit more about it.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: PHP + Mikrotik 5.12

Fri Jan 27, 2012 5:53 pm

The "numbers" argument doesn't accept the exact values you have in Winbox. What in Winbox looks like "0" is in fact a completely unrelated ID in API... kind'a ironic that "numbers" are not accepted in the "numbers" argument.

To get the ID, you need to make a separate print request with an appropriate query, like:
// Si todo va bien mostramos un mensaje.
if ($cliente->sendSync($peticionRed)->getType() !== Response::TYPE_FINAL) {
        // Si no, borramos la red DHCP.
        $peticionRed = new Request('/ip dhcp-server network remove');
        // Entiendo que solo puede haber un DHCP dando gateway y DNS.
        $peticionRed->setArgument("numbers",
                $cliente->sendSync(new Request('/ip dhcp-server network print .proplist=.id', null, Query::where('commnet', 'My network')))->getArgument('.id')
        );
        $cliente->sendSync($peticionRed);

        echo "<p>Red DHCP por defecto eliminada con &eacute;xito.</p>";
        } else {
                  echo "<p>Red DHCP por defecto creada con &eacute;xito.</p>";
        }
} 
Mac clone option? Please tell me a bit more about it.
Many home routers (TP-Link, LynkSys, etc.) have a web configuration interface from which you adjust the router's settings. Since this web interface has a direct access to the network settings (similarly to how you have access to RouterOS' settings), it can see the MAC address behind a certain IP (e.g. the IP the user is accessing the panel with).

Many ISPs (myself included) lock clients based on their device's MAC address. So let's say you're in my network, and suddely decide to buy yourself a router. Instead of notifying me about it and forcing me to change your device's MAC address accordingly, you can change the MAC address of your router's public LAN to be the same as your device's MAC address. To make things easier, instead of forcing you to type your MAC address, the router provides a single button that says "Clone MAC address" which does just that - sees the MAC address associated with your IP, and copies it as your public LAN's MAC address.
 
alopezf1987
just joined
Topic Author
Posts: 8
Joined: Mon Jan 23, 2012 12:09 am

Re: PHP + Mikrotik 5.12

Fri Jan 27, 2012 6:53 pm

The "numbers" argument doesn't accept the exact values you have in Winbox. What in Winbox looks like "0" is in fact a completely unrelated ID in API... kind'a ironic that "numbers" are not accepted in the "numbers" argument.

To get the ID, you need to make a separate print request with an appropriate query, like:
// Si todo va bien mostramos un mensaje.
if ($cliente->sendSync($peticionRed)->getType() !== Response::TYPE_FINAL) {
        // Si no, borramos la red DHCP.
        $peticionRed = new Request('/ip dhcp-server network remove');
        // Entiendo que solo puede haber un DHCP dando gateway y DNS.
        $peticionRed->setArgument("numbers",
                $cliente->sendSync(new Request('/ip dhcp-server network print .proplist=.id', null, Query::where('commnet', 'My network')))->getArgument('.id')
        );
        $cliente->sendSync($peticionRed);

        echo "<p>Red DHCP por defecto eliminada con &eacute;xito.</p>";
        } else {
                  echo "<p>Red DHCP por defecto creada con &eacute;xito.</p>";
        }
} 
Man, that worked like a charm in my proyect! Thanks again (gonna mention your name on my presentation). Now the web page has a "powered by PEAR2_Net_RouterOS" title on it (in Spanish yet).

All right so, things to do:
  • Queues and address lists (also proposed by my teacher).
  • MAC cloning.
  • Translate to English.
  • NAT.
Give me one week (maybe two days) to get over it. Need to have a rest right now, I've been coding all the week.
 
User avatar
Hammy
Forum Veteran
Forum Veteran
Posts: 776
Joined: Fri May 28, 2004 5:53 pm
Location: DeKalb, IL
Contact:

Re: PHP + Mikrotik 5.12

Thu Mar 29, 2012 10:24 pm

How is this coming along?

Who is online

Users browsing this forum: Matta and 20 guests