API PHP package

From MikroTik Wiki
Revision as of 21:44, 24 January 2012 by Boen robot (talk | contribs)
Jump to: navigation, search


The examples on this page use the PEAR2_Net_RouterOS package. You can install it with the PEAR(2) installer, or just download and extract the files from the "src" directory wherever you wish.

All examples assume that the files from the "src" folder are somehow directly accessible to your PHP file (either via editing your include_path, or by simply extracting the contents of the "src" folder where your own PHP file is). Also, the router is assumed to be accessible with a local IP to the device PHP runs from. The client itself could work without these restrictions - they are specified here for clarity.

NOTE: The client requires PHP 5.3.0 or later.

Example 1: An HTML form to make RouterOS ping someone

This example is particularly useful when you want to ping someone from inside the network while browsing the page from outside the network.

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

if (isset($_GET['act'])) {//This is merely to ensure the form was submitted.

    //Adjust RouterOS IP, username and password accordingly.
    $client = new Client('', 'admin', 'password');

    //This is just one approach that allows you to create a multy purpose form,
    //with ping being just one action.
    if ($_GET['act'] === 'Ping' && isset($_GET['address'])) {
        //Ping can run for unlimited time, but for PHP, we need to actually stop it at some point.
        $pingRequest = new Request('/ping count=3');
        $results = $client->sendSync($pingRequest->setArgument('address', $_GET['address']));
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="http://www.w3.org/1999/xhtml">
        <title>Ping someone</title>
            <form action="" method="get">
                        <label for="address">Address:</label>
                        <input type="text" id="address" name="address" value="<?php
                            if (isset($_GET['address'])) echo htmlspecialchars($_GET['address']);
                        ?>" />
                        <input type="submit" id="act" name="act" value="Ping" />
if (isset($_GET['act'])) {//There's no need to execute this if the form was not submitted yet.
    echo '<div>Results:<ul>';
    foreach ($results as $result) {
        //Add whatever you want displayed in this section.
        echo '<li>Time:', $result->getArgument('time'), '</li>';
    echo '</ul></div>';