# HTML encoding proc

**URL:** <https://community.f5.com/t/html-encoding-proc/67139>\
**Category:** Community CodeShare\
**Created:** [March 18, 2015, 12:00am UTC](https://community.f5.com/t/html-encoding-proc/67139 "2015-03-18T00:00:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hoolio](https://avatars.discourse-cdn.com/v4/letter/h/f6c823/32.png) [@hoolio](https://community.f5.com/u/hoolio)\
**Post date:** [March 18, 2015, 12:00am UTC](https://community.f5.com/t/html-encoding-proc/67139/1 "2015-03-18T00:00:38Z")

</div>

**Problem this snippet solves:**

This proc [HTML encodes](http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML) an input string.

See the OWASP discussion page for details on when/how to use this approach: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet)

**How to use this snippet:**

## iRule proc Source

Define the proc named html\_encode in a separate iRule named library:

**Code :**

```auto
rule library {
proc html_encode { str } {
  set encoded ""
  foreach char [split $str ""] {
    switch $char {
      "<" { append encoded "<" }
      ">" { append encoded "<" }
      "'" { append encoded "'" }
      {"} { append encoded """ }
      "&" { append encoded "&" }
      default { append encoded $char }
    }
  }
  return $encoded
}
}

# Call the procedure from another iRule using the name of the iRule where the proc is defined as the namespace and then the name of the procedure (library::html_encode): 

when RULE_INIT {
# iRule that calls the html_encode proc:
set raw {some xss: < script >alert(document.cookie) and sqli: ' or 1==1# "}

log local0. "HTML encoded: [call library::html_encode $raw]"

# Log output
#HTML encoded: <script<alert(document.cookie)</script< and sqli: ' or 1==1# "
}

```

---

<div class="post-metadata">

**Author:** ![wsanders\_233261](https://avatars.discourse-cdn.com/v4/letter/w/e47774/32.png) [@wsanders\_233261](https://community.f5.com/u/wsanders_233261)\
**Post date:** [February 16, 2018, 7:04pm UTC](https://community.f5.com/t/html-encoding-proc/67139/2 "2018-02-16T19:04:13Z")

</div>

Please explain RULE\_INIT.

Can I call a proc anywhere? Like:

when HTTP\_REQUEST { set foo [call library:some\_function “some arg”] …
