1

Topic: htmLawed - how to allow img src only from one folder?

I want to allow img src to be only from one directory, for example "uploads" directory on my page:

<img src="https://example.com/uploads/111.jpg"> - allowed
<img src="https://example.com/admin/222.jpg"> - NOT allowed (because admin folder)
<img src="https://google.com/uploads/333.jpg"> - NOT allowed (because different domain)

How to do that in htmLawed? Thanks.

2

Re: htmLawed - how to allow img src only from one folder?

There are a couple of ways this can be done. One is to use a custom PHP function through htmLawed config.'s hook_tag parameter; the other is to employ htmLawed's spec parameter.

With the latter:

$config = ...
$spec = 'img=src(match=%"//example.com/uploads"%)';
$out = htmLawed($in, $config, $spec);

With this example, if a 'src' value is not permitted, then only the 'src' value is removed; the 'img' tag remains.

3

Re: htmLawed - how to allow img src only from one folder?

Thanks, I decided to go with hook_tag:

function hookTag($element, $attributes = 0) {
  // further filter tags
  // closing tags
  if (is_numeric($attributes)) {
    return "</$element>";
  }
  // only allow images from uploads dir
  if ($element === 'img' && !preg_match('/^http[s]*:\/\/example.com\/uploads\/[a-zA-Z0-9]+\.jpg$/', @$attributes['src'])) {
    $attributes['src'] = 'http://example.com/invalid_image.jpg';
  }
  // convert attributes back to string
  $string = '';
  foreach ($attributes as $k => $v) {
    $string .= " {$k}=\"{$v}\"";
  }
  $empty_elements = array('br' => 1, 'hr' => 1, 'img' => 1);
  return "<{$element}{$string}".(array_key_exists($element, $empty_elements) ? ' /' : '').'>';
}

btw in documentation (https://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/htmLawed_README.htm#s3.4.9) there is error (quotes around my_ should be double and dot should not be there):

$new_element = '<param id='my_'. $id; allowscriptaccess="never" />';

4

Re: htmLawed - how to allow img src only from one folder?

Thanks for pointing out the typo... I will fix it.