Community discussions

MikroTik App
 
LaZyLion
newbie
Topic Author
Posts: 32
Joined: Fri May 09, 2014 10:27 am

A function for url encoding

Sun Jan 08, 2017 1:01 am

Hi all,

I got to playing around with functions and came up with a way to url encode text.
I regularly use /tool fetch to send information to a php script on my web server.
I run my own homemade DYDNS variant and it helps to have the information properly encoded so it arrives intact.


The code:

Create a file called urlencode.fnc
:if ([:len $this ]>0) do={
:local chars " \"%&"; 
:local subs { "%20"; "'"; "%25"; "%26" }
:local that "";
:for i from=0 to=([:len $this]-1) do={ 
	:local s [:pick $this $i];
	:local x [:find $chars $s]
	:if ([:len $x]>0) do={
		:set $s ($subs->$x)	
	}
	:set $that ($that . $s)
}
:return $that;
}


Create another file called test.rsc
# test function

# create fucntion from file
:local urlencode [:parse [/file get [/file find name="url_encoder.fnc"] contents] ];


# string to be tested
:local names "our names are 'bob' & 'doug'";


# usage
:local op [$urlencode this=$names];
:put $op;

Upload both files to your router.


From the CLI type: /import test.rsc

... and voila!



Notes:
You'll notice that this version only encodes four things:
  • space
    double quote
    percent sign
    ampersand
The reason for this is those are the ones I use. You can can add your own as needed:
characters to be subbed go on line 2, and the substitutions on line three.
Make sure you maintain the correct order, formatting and syntax.

There are over 200 characters which can be encoded which would make the script rather long,
so stick to using the ones you expect to need.

See the encoding table here: http://www.w3schools.com/tags/ref_urlencode.asp
Use php urldecode() to restore (or equivalent in whatever language you are using).

Don't let the backslash in line 2 fool you. Double quotes inside double quotes have to 'escaped'.

The function uses the variable $this to get it's parameter, ie: text to be encoded.

Info on functions in RouterOS scripting can be found here: http://wiki.mikrotik.com/wiki/Manual:Sc ... #Functions

Hope someone finds this useful. Happy coding.

Tested on 6.37.3
Jan 2017
 
User avatar
AffinityNetworks
just joined
Posts: 2
Joined: Mon Feb 20, 2017 4:27 pm
Location: Norfolk, United Kingdom
Contact:

Re: A function for url encoding

Mon Feb 20, 2017 9:47 pm

Fantastic, thank you for sharing. :D

Thats a keeper!
 
eminkaplan
just joined
Posts: 4
Joined: Sat May 20, 2017 6:28 am

Re: A function for url encoding

Fri Apr 26, 2019 2:39 am

Thanks, its work on ros 6.44.2

Who is online

Users browsing this forum: jvanhambelgium and 79 guests