Community discussions

MikroTik App
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Mikrotik -> PHP

Thu Jun 23, 2011 4:35 pm

Hello,
I need to help Connect Mikrotik to PHP

I have billing system for users but I can not automatic add, disable, enable or edit users in mikrotik from php

can anyone help me?
 
fewi
Forum Guru
Forum Guru
Posts: 7717
Joined: Tue Aug 11, 2009 3:19 am

Re: Mikrotik -> PHP

Thu Jun 23, 2011 7:10 pm

Look up the API on the wiki.
 
User avatar
Xymelin
just joined
Posts: 9
Joined: Wed Apr 07, 2010 2:13 pm
Location: Riga, Latvia
Contact:

Re: Mikrotik -> PHP

Sun Jun 26, 2011 3:15 am

Hello,
I need to help Connect Mikrotik to PHP

I have billing system for users but I can not automatic add, disable, enable or edit users in mikrotik from php

can anyone help me?
I have some stuff connected with integrating billing with Mikrotik routers. Write an email to me.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Sun Jun 26, 2011 4:06 pm

I want to disable user from php
I wrote this script:
<?php

require('mikrotik.php');

$API = new routeros_api();

$API->debug = true;

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

   $API->write('ip firewall filter add chain=input src-address=13.13.13.13 action=accept disabled=yes');

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

   print_r($ARRAY);

   $API->disconnect();

}


when i open this in browser:
Connection attempt #1 to 123.123.123.123:8728... <<< [6] /login >>> [5/5 bytes read. >>> [5, 39] !done >>> [37/37 bytes read. >>> [37, 1] =ret=6484868b370e2f2c381b06f161e5d226 <<< [6] /login <<< [11] =name=admin <<< [44] =response=0023ad4ee121dab3e5d0e23457ce4dd210 >>> [5/5 bytes read. >>> [5, 1] !done Connected... <<< [85] ip firewall filter add chain=input src-address=13.13.13.13 action=accept disabled=yes >>> [5/5 bytes read. >>> [5, 40] !trap >>> [31/31 bytes read. >>> [31, 8] =message=no such command prefix >>> [5/5 bytes read. >>> [5, 1] !done Array ( [!trap] => Array ( [0] => Array ( [message] => no such command prefix ) ) ) Disconnected...

can anyone help me?
 
reverged
Member Candidate
Member Candidate
Posts: 270
Joined: Thu Nov 12, 2009 8:30 am

Re: Mikrotik -> PHP

Mon Jun 27, 2011 7:42 am

<?php

require('mikrotik.php');

$API = new routeros_api();

$API->debug = true;

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

   $API->write('ip firewall filter add chain=input src-address=13.13.13.13 action=accept disabled=yes');

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

   print_r($ARRAY);

   $API->disconnect();

}
Take a look at the examples in the wiki. API command syntax is different than cli. The above command would be written something like this:
   $API->write('/ip/firewall/filter/add', false);         //this is the basic command; false says the there are more lines to the command.
   $API->write('=chain=input',false);                    // this is another part of the command
   $API->write('=src-address=13.13.13.13',false);  // more
   $API->write('=action=accept', false);                  //more
   $API->write('=disabled=yes');                         //all done; 
The command is a single line and then parameters are additional lines.
Why do you want it disabled?
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Mon Jun 27, 2011 6:55 pm

reverged
Thank you 8)
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Wed Jun 29, 2011 7:09 pm

ok Thank you, I add firewall entry and is it ok.
but when I need to change firewall entry I had problem...
I can not send correct "number".

for example when I type from putty command is:
ip firewall filter set action=drop numbers=2
from php I think script is:
$API->write('/ip/firewall/filter/set', false);
$API->write("=action=drop",false);                  
$API->write("=numbers=2");
but I have error:
. <<< [23] /ip/firewall/filter/set <<< [13] =disabled=yes <<< [10] =numbers=2 >>> [5/5 bytes read. >>> [5, 42] !trap >>> [11/11 bytes read. >>> [11, 30] =category=0 >>> [21/21 bytes read. >>> [21, 8] =message=no such item >>> [5/5 bytes read. >>> [5, 1] !done Array ( [!trap] => Array ( [0] => Array ( [category] => 0 [message] => no such item ) ) ) Disconnected

What can I do?

thank you in advance :)
 
reverged
Member Candidate
Member Candidate
Posts: 270
Joined: Thu Nov 12, 2009 8:30 am

Re: Mikrotik -> PHP

Fri Jul 01, 2011 6:10 am

ip firewall filter set action=drop numbers=2

from php I think script is:
$API->write('/ip/firewall/filter/set', false);
$API->write("=action=drop",false);                  
$API->write("=numbers=2");
"numbers" don't work in api, afaict. You have to find the ".id" of the filter rule first, then use that to change the rule.
$API->write("/ip/firewall/filter/print");
Will return all the filter rules including the .id's. They are hex values with an asterisk. The asterisk is important.

You can put search criterion on the print command, such as sending this text as the second line of the command:
$API->write("?src-address=13.13.13.13");
Then you will only see .id's for items having that source address. Remember to put 'false' as the second parameter to the /ip/firewall/filter/print command.....

Then use:
$API->write('/ip/firewall/filter/set', false);
$API->write("=.id=<the id goes here>", false);
$API->write("=action=drop");                  
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Sat Jul 23, 2011 9:51 pm

Thank you very much, but I still need your help

1. $API->write('/ip/firewall/filter/add',false);
1. $API->write('=chain=forward',false);
1. $API->write("=src-address=$ip",false);
1. $API->write('=action=accept',false);
1. $API->write('=comment='.$abonenti.'',false);
1. $API->write("=src-mac-address=$maci",false);
1. $API->write('=place-before=0',false);
1. $API->write('=disabled=no');



2. $API->write('/ip/firewall/filter/add',false);
2. $API->write('=chain=forward',false);
2. $API->write("=src-address=$ip",false);
2. $API->write('=action=accept',false);
2. $API->write('=comment='.$abonenti.'',false);
2. $API->write("=src-mac-address=$maci",false);
2. $API->write('=disabled=no');

I need to add filter rule on the top of the table. because at the bottom I hav DROP rule, and I need to add rule before the DROP.

for this I write "1" script, and it is not working... "$API->write('=place-before=0',false);" because this command...

everything else is write, because 2 script is working, but it adds rule at the bottom...


how can I add filter rule at the top of the table?


thank you in advance.
 
User avatar
janisk
MikroTik Support
MikroTik Support
Posts: 6263
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Mikrotik -> PHP

Mon Jul 25, 2011 8:54 am

firewall rules are printed out in order they are in, so , you have to get .ID of the first rule in the chain (in the firewall) and use that in place-before. in CLI you can use console numbering, but in API you have to refer to item .id field or to item name.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Fri Jul 29, 2011 4:40 am

Thank you for your answer, but I didn't understand little.
exactly what is .id?
as you see in attached picture .id is the number witch is under #. I understand correct?

and my script is following:
 $API->write('/ip/firewall/filter/add',false);
   $API->write('=chain=forward',false);
   $API->write("=src-address=$ip",false);
   $API->write('=action=accept',false);
   $API->write('=comment='.$abonenti.'',false);
   $API->write("=src-mac-address=$maci",false);
   $API->write("=place-before=.0",false);
   $API->write('=disabled=no');
but it is not working...

please is you know help me..

thank you...
You do not have the required permissions to view the files attached to this post.
 
User avatar
janisk
MikroTik Support
MikroTik Support
Posts: 6263
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Mikrotik -> PHP

Fri Jul 29, 2011 9:44 am

usually .id value is star with hex number, here are some examples
*2DA
*2
*A
so when you get results of this command:
/ip/firewall/print
=.proplist=.id
you will get list like this:
=.id=*A
=.id=*B
=.id=*C
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Mon Aug 15, 2011 3:48 pm

janisk
can you send me some example?
 
User avatar
janisk
MikroTik Support
MikroTik Support
Posts: 6263
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Mikrotik -> PHP

Mon Aug 15, 2011 4:24 pm

it is not clear what example i can give you?

firewall rules are in strict order, so print, and first one will be the correct one, or add some comment to tag the real first rule if you are in doubt.

Commands you use are correct, just values you are placing in are not.

in previous post i gave you examples on how these .id field values looks like - it is star with hex number following that start.

so in short - .id field value you should use to address entries when using API have "*" as a prefix and HEX number afterwards, like *1, *2, *3 .. *A ... *F,*10

you can go and use python API example client where you will see clearly, what you send router and what exactly router replies.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Mon Sep 26, 2011 9:25 pm

Hello

I need to remove DROP filter rule from mikrotik, you can see on picture, I made comment "000009".
I have this script, But I have error...
Can you correct my script and write me exactly script for my situation.

Thank you in Advance..

<?
require('routeros_api.class.php');
$API = new routeros_api();
$API->debug = true;
include "router_config.php";


$API->write('/ip/firewall/filter/remove',false);
$API->write('=comment=000009');

$READ = $API->read(false);
$ARRAY = $API->parse_response($READ);
print_r($ARRAY);
$API->disconnect();
?>
You do not have the required permissions to view the files attached to this post.
 
User avatar
janisk
MikroTik Support
MikroTik Support
Posts: 6263
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Mikrotik -> PHP

Wed Sep 28, 2011 8:44 am

$API->write('/ip/firewall/filter/print',false);
$API->write('?comment=000009');
return will print whole entry where comment is as in querry.
if you will use proplist, then you can limit output to just .id field

when you have the .id, you can remove the item
$API->write('/ip/firewall/filter/remove',false);
$API->write('=.id=*HEXNUM');
 
AbSSoLuT
just joined
Posts: 7
Joined: Sun May 29, 2011 6:34 pm

Re: Mikrotik -> PHP

Tue Oct 04, 2011 2:25 pm

Hello,
I need to help Connect Mikrotik to PHP

I have billing system for users but I can not automatic add, disable, enable or edit users in mikrotik from php

can anyone help me?
Can u share billing system ? If yes send me pm with link
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue Oct 04, 2011 2:30 pm

Hello,
thank you for this

so I want to edit by php api some filter rulls, for example edit filter rull's sourse ip address.
can you write for me this script?
Can u share billing system ? If yes send me pm with link
now its only beta version
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Wed Oct 05, 2011 1:19 pm

so I want to edit by php api some filter rulls, for example edit filter rull's sourse ip address.
can you write for me this script?
   $API->write('/ip/firewall/filter/edit',false);
   $API->write("=.id=$id",false);
   $API->write("=src-address=$ip",false);
   $API->write("=src-mac-address=$maci");
 
User avatar
janisk
MikroTik Support
MikroTik Support
Posts: 6263
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Mikrotik -> PHP

Wed Oct 05, 2011 2:00 pm

yes, that looks reasonable, you just have to get correct value for .id field to address correct rule.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Wed Oct 05, 2011 2:48 pm

I get this error:
Connection attempt #1 to 123.123.123.123:8728... <<< [6] /login >>> [5/5 bytes read. >>> [5, 39] !done >>> [37/37 bytes read. >>> [37, 1] =ret=a58048c26a26d61fde722fce4750f34f <<< [6] /login <<< [11] =name=admin <<< [44] =response=00b54e6533572cc9a3992c023e24fddfd8 >>> [5/5 bytes read. >>> [5, 1] !done Connected... <<< [24] /ip/firewall/filter/edit <<< [10] =.id=00001 <<< [26] =src-address=12.34.12.34 <<< [17] =src-mac-address= >>> [5/5 bytes read. >>> [5, 35] !trap >>> [26/26 bytes read. >>> [26, 8] =message=unknown parameter >>> [5/5 bytes read. >>> [5, 1] !done Array ( [!trap] => Array ( [0] => Array ( [message] => unknown parameter ) ) ) Disconnected...
I cant understand what is mistake
 
User avatar
janisk
MikroTik Support
MikroTik Support
Posts: 6263
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Mikrotik -> PHP

Wed Oct 05, 2011 3:13 pm

<<< [10] =.id=00001
this is the problem. attribute .id value is hexadecimal number without leading zeros prefixed with *

for example =.id=*BEEF

that is the problem why you cannot do what you require.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue Nov 22, 2011 9:17 pm

I understand that I need hex, but I do not know hex coding,

ex. I want need to edit user 1234
What can I make?
$API->write('/ip/firewall/filter/edit',false);
$API->write("=.id=1234",false);
$API->write("=src-address=$ip",false);
$API->write("=src-mac-address=$mac");
Thank you
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue Nov 22, 2011 9:43 pm

There's PHP's dechex() function to help you out with this. Just remember to prefix the number with a *, i.e.
$API->write('/ip/firewall/filter/edit',false);
$API->write("=.id=*" . dechex(1234), false);
$API->write("=src-address=$ip",false);
$API->write("=src-mac-address=$mac"); 
However, the hex IDs are not necesarily the same decimal IDs you see in Winbox's "#" column. If you don't have some other sort of a unique identifier, you'll have to first print all entries, and then hardcode the ID you wish to edit. If you do have some sort of a unique identifier (e.g. if the full properties of the filter have their old values only in that one rule), you can print the ID of that directly as you're about to edit it.

That last one is done much easier with my client than with this one, but it's completely doable with this one too.

BTW, on a side note... have you considered using address lists instead of creating actual rules? You can have one rule for enabled users, and perhaps one for disabled users. For MAC address protection, there's the "reply-only" option you can set on your local interface's "ARP" setting, and then add the user's IP/MAC combos into your ARP list. With that setup, once you create a user, enabling and disabling them is a matter of moving a user from the list of enabled to the list of disabled users.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Wed Nov 23, 2011 2:17 pm

Thank you boen_robot!

I make this
   $API->write('/ip/firewall/filter/edit',false);
   $API->write("=.id=*" . dechex(3015), false);
   $API->write("=src-address=$ip",false);
   $API->write("=src-mac-address=$maci");
But I get some error:
Connection attempt #1 to 123.1.1.1:8728... <<< [6] /login >>> [5/5 bytes read. >>> [5, 39] !done >>> [37/37 bytes read. >>> [37, 1] =ret=ebab08056bea7de07c8ced7c4853c44c <<< [6] /login <<< [11] =name=admin <<< [44] =response=00c4a05c93495a60d067f7e8520ff3659d >>> [5/5 bytes read. >>> [5, 1] !done Connected... <<< [24] /ip/firewall/filter/edit <<< [9] =.id=*bc7 <<< [26] =src-address=172.31.247.40 <<< [17] =src-mac-address= >>> [5/5 bytes read. >>> [5, 35] !trap >>> [26/26 bytes read. >>> [26, 8] =message=unknown parameter >>> [5/5 bytes read. >>> [5, 1] !done Array ( [!trap] => Array ( [0] => Array ( [message] => unknown parameter ) ) ) Disconnected...

I want to edit IP address:
http://s008.radikal.ru/i304/1111/d4/ca619f5995b9.png
Sorry and thank you again.
 
User avatar
janisk
MikroTik Support
MikroTik Support
Posts: 6263
Joined: Tue Feb 14, 2006 9:46 am
Location: Riga, Latvia

Re: Mikrotik -> PHP

Wed Nov 23, 2011 2:37 pm

use set instead ofedit as that is interactive and interactive stuff does not work in API.

So anything that in CLI asks for user input will not work properly if at all.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Sat Nov 26, 2011 5:37 pm

In addition to janisk's note, I'm not sure about your ID, as I already said in my last post. 3015 is definetly not it though... that's a comment, not an ID.

With the client from my signature, you should be able to do what you want with something like:
<?php
namespace PEAR2\Net\RouterOS;//This must remain at the top of your PHP file!
require_once 'PEAR2/Net/RouterOS/Autoload.php';

//The rest of your PHP script here... particularly important is that you define $ip and $mac

$client = new Client('123.123.123.123', 'admin', 'root'));

//The key bit... getting the correct ID by printing it
$id = $client->sendSync(new Request('/ip/firewall/filter/print .proplist=.id', null, Query::where('comment', '3015')))->getArgument('.id');

$setRequest = new Request('/ip/firewall/filter/set');
$setRequest->setArgument('numbers', $id);
$setRequest->setArgument('src-address', $ip);
$setRequest->setArgument('src-mac-address', $mac);

$client->sendSync($setRequest);
//And you're done.
 
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Mon Nov 28, 2011 5:05 pm

Hello,
Thank you boen_robot and janisk for answers.

boen_robot, I see your script, but I need this modification
require('routeros_api.class.php'); // RouterOS API class
$API = new routeros_api();
$API->debug = true;
include "router_config.php"; // router username and password

{

$abonentiAPI = $API->connect(new Request('/ip/firewall/filter/print .proplist=.id', null, Query::where('comment', "$abonenti")))->getArgument('.id');

  
$setRequest = new Request('/ip/firewall/filter/set');
$setRequest->setArgument('numbers', $abonentiAPI);
$setRequest->setArgument('src-address', $ip);
$setRequest->setArgument('src-mac-address', $maci);
$client->sendSync($setRequest);

}
   
$READ = $API->read(false);
$ARRAY = $API->parse_response($READ);
print_r($ARRAY);
$API->disconnect();
 
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Mon Nov 28, 2011 5:33 pm

This won't work. Denis' class doesn't have any of my features. The two packages are completely incompatible with each other. You must forget about these lines:
require('routeros_api.class.php'); // RouterOS API class
$API = new routeros_api();
$API->debug = true;
include "router_config.php"; // router username and password
 
in favor of
<?php
namespace PEAR2\Net\RouterOS;//This must remain at the top of your PHP file!
require_once 'PEAR2/Net/RouterOS/Autoload.php';
 
If you wish to keep using Denis' class, you'll have to rewrite the whole communication flow accordingly. The basic idea is the same - use query words to print the entry you're about to edit, get its ID, and feed it into the "numbers" argument of a new set command. You must do this in a "raw" fashion though (i.e. read the API page in the MikroTik Wiki, and write the words accordingly).

My package tries to discourage this (in favor of classes and methods with self descriptive purposes chained in a fashion that should be intuitive to an average PHP developer), while Denis' class only allows for raw kind of flow. I'd rather help you set up my class and do any raw-to-method rewrites than help you with the method-to-raw rewrite.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue Dec 20, 2011 3:19 pm

boen_robot
Can you upload all files?
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Sat Dec 24, 2011 1:40 pm

They're already uploaded at GitHub and SourceForge. See my signature or the bottom of the API page. On both sites, the files are equivalent.


I mean... look
|
|
V
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue Dec 27, 2011 7:40 pm

I get some error and I delete this "namespace PEAR2\Net\RouterOS;"

but now have this error:
Fatal error: Uncaught exception 'LogicException' with message 'Function '__NAMESPACE__\autoload' not found' in /home/fastnetg/public_html/baza/api/PEAR2/Net/RouterOS/Autoload.php:56 Stack trace: #0 /home/f/public_html/test/api/PEAR2/Net/RouterOS/Autoload.php(56): spl_autoload_register() #1 /home/f/public_html/test/api/callback-and-loop.php(2): require_once('/home/fastnetg/...') #2 {main} thrown in /home/f/public_html/test/api/PEAR2/Net/RouterOS/Autoload.php on line 56
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Wed Dec 28, 2011 2:17 pm

You need to have PHP 5.3.0 or later. The error you first saw can only mean that you have an earlier version (e.g. 5.2.*).

If you're doing this on your own machine, upgrade your PHP. If you're using a host, ask your host to upgrade the PHP version for your site.

Don't forget to add back the "namespace PEAR2\Net\RouterOS;" line once that is done.
 
comal
just joined
Posts: 5
Joined: Thu Dec 08, 2011 2:20 pm

Re: Mikrotik -> PHP

Wed Jan 11, 2012 1:52 pm

How can I show the $ARRAY[0][.id] value? The .id make error because the "." character is invalid.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Wed Jan 11, 2012 6:20 pm

How can I show the $ARRAY[0][.id] value? The .id make error because the "." character is invalid.
Quote the key, i.e.
$ARRAY[0]['.id'] 
This is a common requirement for ALL strings (i.e. text) in PHP. You can use either single quotes (apostrophes) as above, or double quotes, although I'd personally reccomend single, because they are interpreted literally (as opposed to double quoted strings, with which variables are expanded). That would in turn save you some trouble later on.

BTW, next time, you might want to make a new topic instead of snatching another user's topic... your issues are not really related anyway.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Wed Jan 11, 2012 7:29 pm

boen_robot
You need to have PHP 5.3.0 or later. The error you first saw can only mean that you have an earlier version (e.g. 5.2.*).

If you're doing this on your own machine, upgrade your PHP. If you're using a host, ask your host to upgrade the PHP version for your site.

Don't forget to add back the "namespace PEAR2\Net\RouterOS;" line once that is done.
Thank you, I'll try PHP 5.3
 
comal
just joined
Posts: 5
Joined: Thu Dec 08, 2011 2:20 pm

Re: Mikrotik -> PHP

Thu Jan 12, 2012 10:03 am

How can I show the $ARRAY[0][.id] value? The .id make error because the "." character is invalid.
Quote the key, i.e.
$ARRAY[0]['.id'] 
This is a common requirement for ALL strings (i.e. text) in PHP. You can use either single quotes (apostrophes) as above, or double quotes, although I'd personally reccomend single, because they are interpreted literally (as opposed to double quoted strings, with which variables are expanded). That would in turn save you some trouble later on.

BTW, next time, you might want to make a new topic instead of snatching another user's topic... your issues are not really related anyway.
Thank you your answer! Your say right, I had to make a new topic. Sorry for all users! :(
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Sat Mar 24, 2012 4:51 pm

Hello,

I need graphic statistic on my billing system, example:
http://i054.radikal.ru/1203/2a/07edab5ca9cc.png

also I need ping from router, example:
http://s019.radikal.ru/i608/1203/fa/84757663d338.png

Is it possible from API? or what is alternative way?
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Sat Mar 24, 2012 9:56 pm

Pinging from router is trivial. You just use the "/ping" command, with arguments equivalent to those you'd use from terminal (address, timeout, etc.).

As for the stats... depends on the kind of stats you want, but either way, you can only get the data for the stats, not a graphic. You need to use a separate charting library that would take the data and generate a graphic out of it, which isn't exactly trivial, but could be made easier if you use a specialized library. Here's a tutorial on pChart for example.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Wed Apr 11, 2012 1:04 pm

Hello,

Now I'm rewriting billing and making for boen_robot API client.
<?php
namespace PEAR2\Net\RouterOS;

require_once 'PEAR2/Net/RouterOS/Autoload.php';

$client = new Client('1.2.3.4', 'admin', '123456');

$addRequest = new Request('/ip/firewall/filter/add');
$addRequest->setArgument('chain', 'forward');
$addRequest->setArgument('src-address', "$ip");
$addRequest->setArgument('action', 'accept');
$addRequest->setArgument('comment', "$abonenti");
$addRequest->setArgument('src-mac-address', "$mac");
$addRequest->setArgument('disabled', 'no');
$addRequest->setTag('arp1');
$client->sendAsync($addRequest);

$addRequest = new Request('/ip/firewall/filter/add');
$addRequest->setArgument('chain', 'forward');
$addRequest->setArgument('dst-address', "$ip");
$addRequest->setArgument('action', 'accept');
$addRequest->setArgument('comment', '$abonenti - 2');
$addRequest->setArgument('disabled', 'no');
$addRequest->setTag('arp2');

$client->sendAsync($addRequest);

$client->loop();
?>
Now I need choices position,
Now I have this:
http://s019.radikal.ru/i635/1204/d5/7cd18fe79787.png
last added want up to "123456789"
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Wed Apr 11, 2012 5:23 pm

There is the "move" command on some menus... the "/ip/firewall/filter" has it at least.

You use it by getting the IDs of the entry to be moved (in the "numbers" argument), and the entry to place that entry before (in the "destination" argument).

So for example, to place an entry (one with $abonenti as its comment) at the top of the list, you'd do:
$printRequest = new Request('/ip/firewall/filter/print');
$printRequest->setArgument('.proplist', '.id');

$destinationId = $client->sendSync($printRequest)->getArgument('.id');

$printRequest->setQuery(Query::where('comment', $abonenti));
$sourceId = $client->sendSync($printRequest)->getArgument('.id');

$moveRequest = new Request('/ip/firewall/filter/move');
$moveRequest->setArgument('numbers', $sourceId);
$moveRequest->setArgument('destination', $destinationId);
$client->sendSync($moveRequest); 
If you need to move an entry before a specific item (not simply the first one), you'd have to use setQuery() before the $destinationId line. There, you'd specify a query that uniquely identifies the item you're targeting as destination.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Fri Apr 13, 2012 6:50 pm

boen_robot thank you!
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Wed Apr 25, 2012 7:04 pm

Hi,
I need edit user. I was commented each user and I want send command with comment
I want to edit IP, MAC or Comment


Thanks
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Thu Apr 26, 2012 4:19 am

This is in what menu? Still /ip/firewall/filter?

Anyway... to edit any entry in any list, you need to first get its ID, and pass it to a "set" command's "numbers" argument. The other arguments in the "set" command reflect the properties you wish to modify and their new values.

To get the ID, you "print" an entry targeted with a query.

So, something like:
$printRequest = new Request('/ip/firewall/filter/print');
$printRequest->setArgument('.proplist', '.id');
$printRequest->setQuery(Query::where('comment', $abonenti));
$id = $client->sendSync($printRequest)->getArgument('.id');

$setRequest = new Request('/ip/firewall/filter/set');
$setRequest
    ->setArgument('numbers', $id)
    ->setArgument('src-address', $ip)
    ->setArgument('src-mac-address', $mac)
    ->setArgument('comment', $newAbonenti);
$client->sendSync($setRequest);
 
(NOTE: $abonenti is supposed to contain the actual comment identifying the user; $ip contains the new IP you want, $mac contains the new MAC you want, and $newAbonenti contains the new comment you want)

In case you haven't figured out the pattern yet - any time there's "numbers" in shell, in API there's a print request with a query. See this tutorial for details.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 01, 2012 6:56 pm

boen_robot thank you
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Fri May 04, 2012 2:08 pm

Hello,

I need update queue, I make this but do not working:
    $resultpackupdate = mysql_query("SELECT * FROM packets WHERE router='".$row['router']."' and packetid='".$packetid."'");
    while($rowpackupdate = mysql_fetch_assoc($resultpackupdate))
    {
    $printRequest = new Request('/ip/firewall/filter/print');
    $printRequest->setArgument('.proplist', '.id');
    $printRequest->setQuery(Query::where('comment', $abonenti));
    $id = $client->sendSync($printRequest)->getArgument('.id');
    
    $setRequest = new Request('/queue/simple/set');
    $setRequest
        ->setArgument('numbers', $id)
        ->setArgument('max-limit', $rowpackupdate["local"])
        ->setArgument('comment', $abonenti . ' L');
    $client->sendSync($setRequest);

    $setRequest = new Request('/queue/simple/set');
    $setRequest
        ->setArgument('numbers', $id)
        ->setArgument('max-limit', $rowpackupdate["global"])
        ->setArgument('comment', $abonenti . ' G');
    $client->sendSync($setRequest);
    } 
Please help me
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue May 08, 2012 11:06 am

An ID you get in one menu is only useful for that one menu.

You're trying to use an ID from the "/ip/firewall/filter" menu in the "/queue/simple" menu. Further more, you're using that same ID twice... this means you're modifying the same entry twice.

I'm going to go on a limb here and assume what you really want is to modify two different queues that you identify with two distinct comments. For that, you need to print each, and set each, like:
    $printRequest = new Request('/queue/simple/print');
    $printRequest->setArgument('.proplist', '.id');
    
    $setRequest = new Request('/queue/simple/set');

    $resultpackupdate = mysql_query("SELECT * FROM packets WHERE router='".$row['router']."' and packetid='".$packetid."'");
    while($rowpackupdate = mysql_fetch_assoc($resultpackupdate))
    {

    $printRequest->setQuery(Query::where('comment', $abonenti . ' L'));
    $id = $client->sendSync($printRequest)->getArgument('.id');

    $setRequest
        ->setArgument('numbers', $id)
        ->setArgument('max-limit', $rowpackupdate["local"]);
    $client->sendSync($setRequest);

    $printRequest->setQuery(Query::where('comment', $abonenti . ' G'));
    $id = $client->sendSync($printRequest)->getArgument('.id');

    $setRequest
        ->setArgument('numbers', $id)
        ->setArgument('max-limit', $rowpackupdate["global"]);
    $client->sendSync($setRequest);
    } 
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 08, 2012 4:34 pm

First thank you for reply.

I try this but do not work, when I add this:
print $id;

Does not showing ID.
I think can not find ID
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue May 08, 2012 6:43 pm

This can only mean there's no entry matching the query...

Are you sure there's a queue with that comment? Perhaps it's the queues' name instead?

Let's check that out... try it like this:
    $printRequest = new Request('/queue/simple/print');
    $printRequest->setArgument('.proplist', '.id');
    
    $setRequest = new Request('/queue/simple/set');

    $lAbonentiQuery = Query::where('name', $abonenti . ' L');
    $gAbonentiQuery = Query::where('name', $abonenti . ' G');

    $resultpackupdate = mysql_query("SELECT * FROM packets WHERE router='".$row['router']."' and packetid='".$packetid."'");
    while($rowpackupdate = mysql_fetch_assoc($resultpackupdate))
    {

    $printRequest->setQuery($lAbonentiQuery);
    $id = $client->sendSync($printRequest)->getArgument('.id');

    $setRequest
        ->setArgument('numbers', $id)
        ->setArgument('max-limit', $rowpackupdate["local"]);
    $client->sendSync($setRequest);

    $printRequest->setQuery($gAbonentiQuery);
    $id = $client->sendSync($printRequest)->getArgument('.id');

    $setRequest
        ->setArgument('numbers', $id)
        ->setArgument('max-limit', $rowpackupdate["global"]);
    $client->sendSync($setRequest);
    } 
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 08, 2012 6:49 pm

boen_robot
Now I test it and works

Thank you for help me!
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Sun May 13, 2012 3:57 pm

Hello,

I need to make this in PHP graphics

Image

Can anyone help me?

Thanks
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Sun May 13, 2012 6:08 pm

What do you mean by "PHP graphics"? A chart? I already told you about that in an earlier post in this topic. If you mean an HTML table... how do you want the table to look? If you can write it in plain HTML, I could help you make PHP generate that HTML.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Mon May 14, 2012 7:15 pm

Hello,

yes I'm interesting chart, example

http://pchart.sourceforge.net/screenshots.php?ID=21
Image

and there was LAN2 statistic

sorry for my English.
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue May 15, 2012 2:12 am

With PHP, you can't really get "live" data simply due to the fact PHP is over as soon as it displays stuff. You can however collect data, and visualize it at a later point.

You have a choice - either let PHP run for a few seconds, and let it display the stats for those few seconds, or let a separate PHP file collect data continiously into a database, and have a separate script visualize this data out of the database. The former is easier, but is useless for most scenarios, and I'm assuming this includes yours too. So let's try the second one...

First, the DB. Do this query (once) to setup a table for the stats:
CREATE  TABLE IF NOT EXISTS `stats` (
  `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
  `rx-bits-per-second` INT UNSIGNED NOT NULL ,
  `tx-bits-per-second` INT UNSIGNED NOT NULL ,
  PRIMARY KEY (`time`) )
ENGINE = InnoDB;
(add any additional columns for stuff you want to graph, and adjust codes below accordingly)

Then, create a PHP file that will connect to RouterOS and collect data. I'm going to use the MySQLi extension, with its prepared statements, and I highly reccomend you do too (at least for performance's sake):
<?php
namespace PEAR2\Net\RouterOS;
require_once 'PEAR2/Net/RouterOS/Autoload.php';

try {
    $client = new Client('1.2.3.4', 'admin', '123456');
    $mysqli = new \mysqli('localhost', 'root', '', 'db');
} catch (\Exception $e) {
    die('Connection error: ' . $e);
}

$insertQuery = $mysqli->prepare('INSERT INTO `stats` (`rx-bits-per-second`, `tx-bits-per-second`) VALUES (?, ?)');
$insertQuery->bind_param('ii', $rx_bits_per_second, $tx_bits_per_second);

$monitor = new Request('/interface monitor-traffic interval=1s interface=LAN2 .proplist=rx-bits-per-second,tx-bits-per-second');
$monitor->setTag('m');

$client->sendAsync($monitor, function($response) use ($insertQuery, $rx_bits_per_second, $tx_bits_per_second) {
    $rx_bits_per_second = $response->getArgument('rx-bits-per-second');
    $tx_bits_per_second = $response->getArgument('tx-bits-per-second');
    $insertQuery->execute();
});

//Start monitoring... indefinetly
$client->loop(); 
Run this file either on a different computer from your web server, or keep it there, running in the background (keeping in mind that it will slow your server down a little).

When you want to visualize the data as an image, use a separate file (which would be executed only at visualization time, i.e. from an "img" element at a third file), like:
<?php
//Prepare the required chart library
require_once 'pChart/class/pDraw.class.php';
require_once 'pChart/class/pImage.class.php';
require_once 'pChart/class/pData.class.php';

//Connect to the DB to get the data
try {
    $mysqli = new mysqli('localhost', 'root', '', 'db');
} catch (\Exception $e) {
    die('Connection error: ' . $e);
}

//Get the data from the DB
$time = $rx_bits_per_second = $tx_bits_per_second = array();
$result = $mysqli->query('SELECT `time`, `rx-bits-per-second`, `tx-bits-per-second` FROM `stats`');
while ($row = $result->fetch_assoc()) {
    $time[] = $row['time'];
    $rx_bits_per_second[] = $row['rx-bits-per-second'];
    $tx_bits_per_second[] = $row['tx-bits-per-second'];
}

//Assign the gathered data as the one to be charted
$stats = new pData();
$stats->addPoints($time, 'Time');
$stats->addPoints($rx_bits_per_second, 'rx-bits-per-second');
$stats->addPoints($tx_bits_per_second, 'tx-bits-per-second');

//Set display settings for the time
$stats->setAbscissa('Time');
$stats->setXAxisName('Time');
$stats->setXAxisDisplay(AXIS_FORMAT_TIME, 'H:i:s');

//Set display settings for the RX bps
$stats->setSerieOnAxis('rx-bits-per-second', 0);
$stats->setAxisName(0, 'RX');
$stats->setAxisUnit(0, 'bps');

//Set display settings for the TX bps
$stats->setSerieOnAxis('tx-bits-per-second', 1);
$stats->setAxisName(1, 'TX');
$stats->setAxisUnit(1, 'bps');

//Put the stats into a chart, and set the different dimensions and scales
$chart = new pImage(700, 230, $stats);
$chart->setGraphArea(60, 40, 670, 190);
$chart->drawScale();

//Make it an area chart
$chart->drawAreaChart();

//Done. Send it to the browser.
$chart->Stroke(); 


DISCLAIMER: I haven't tested any of this... but at least in theory, it should work.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 15, 2012 4:32 pm

boen_robot first thank you again and again.

I'll try it and I get this error:
Fatal error: Maximum execution time of 30 seconds exceeded in C:\Program Files\VertrigoServ\www\billing\code\PEAR2\Net\Transmitter\Stream.php on line 300
And do not inserting in SQL.


Thank you
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue May 15, 2012 4:35 pm

The first PHP file needs to run from the command line, not from a web page. While it is running from a command line, the second one is to be opened from a browser.

The message you saw occured because you were running it from a browser. From a browser, there is a limit on how long a PHP file can run.


Also make sure you have MySQLi enabled and have created the "stats" table prior to running either file.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 15, 2012 4:40 pm

I think I do not have MySQLi on my windows server. I'm install it and try again.

Thank you
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 15, 2012 4:46 pm

I think I do not have MySQLi on my windows server. I'm install it and try again.

Thank you
Can I integration it on MySQL?

Thanks
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue May 15, 2012 4:54 pm

You could, but it would be very slow. Running the file above would slow down your server just a little. Running a file with the MySQL extension would slow things down significantly.

You should already have the MySQLi extension. You just need to enable it by opening php.ini and uncommenting the line "extension=php_mysqli.dll".
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 15, 2012 5:00 pm

Now I'll check php.ini and there was this function "extension=php_mysqli.dll"

I can't understand how to run this script without browser

Thank you
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue May 15, 2012 5:04 pm

To open the command line, go to "Start > (All) Programs > Accessories > Command Prompt".

In the new window, type the path to "php.exe", followed by "-f" and the location of the PHP file.

For example, if php.exe is at "C:\Program Files\VertrigoServ\PHP\php.exe" and the PHP file is at "C:\Program Files\VertrigoServ\www\billing\code\monitor.php", type
"C:\Program Files\VertrigoServ\PHP\php.exe" -f "C:\Program Files\VertrigoServ\www\billing\code\monitor.php"
and hit Enter.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 15, 2012 5:08 pm

Thank you, I'll try it.

Example when I need this in linux, can I use cron?
 
User avatar
boen_robot
Forum Guru
Forum Guru
Posts: 2400
Joined: Thu Aug 31, 2006 4:43 pm
Location: europe://Bulgaria/Plovdiv

Re: Mikrotik -> PHP

Tue May 15, 2012 5:09 pm

Thank you, I'll try it.

Example when I need this in linux, can I use cron?
Yes. Just set the cron to run once, rather than on intervals.
 
giobulia
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 52
Joined: Thu Jun 23, 2011 4:30 pm

Re: Mikrotik -> PHP

Tue May 15, 2012 10:26 pm

Thank you!!! :roll:

Who is online

Users browsing this forum: No registered users and 58 guests