how to htmlencode this string to help prevent javascript injections?

2 posts by 2 authors in: Forums > CMS Builder
Last Post: July 18, 2022   (RSS)

By Codee - July 16, 2022 - edited: July 16, 2022

Hello all,

I am wanting to htmlencode the following piece of code so as to help prevent against javascript injections. Any clues? It's a piece of code used in displaying page number navigation. The $blogMetaData part is throwing me off and my head's getting sore from banging the wall.

<div class="blogpagenumber">
  <?php if ($blogMetaData['invalidPageNum']): ?>
    Results page '<?php echo $blogMetaData['page'] ?>' not found, <a href="<?php echo $blogMetaData['firstPageLink'] ?>">start over &gt;&gt;</a>.<br><br>
  <?php elseif (!$blogRecords): ?>
    <br>
    Those records are not currently available.  Please click BACK in your browser.<br><br>
  <?php endif ?>
  <?php if ($blogMetaData['prevPage']): ?>
    <a href="<?php echo $blogMetaData['prevPageLink'] ?>">&lt;&lt;&nbsp;previous&nbsp;</a>
    <?php else: ?>
  <?php endif ?> 
  <?php
	  if (@!$_GET['page']): $current_page = "1";
	  else: $current_page = $_GET['page'];
	  endif;
  ?>
  <?php foreach (range(1, $blogMetaData['totalPages']) as $page): ?>
    <?php if ($page == $current_page): ?>
      <span class="blogbordertext">&nbsp;page&nbsp;<?php echo $page; ?>&nbsp;</span>
      <?php else: ?>
        <a href="?<?php echo http_build_query(array_merge($_REQUEST, array('page' => $page))) ?>"><?php echo $page; ?></a>
    <?php endif ?> 
  <?php endforeach; ?>
  <?php if ($blogMetaData['nextPage']): ?>
    <a href="<?php echo $blogMetaData['nextPageLink'] ?>">&nbsp;next&nbsp;&gt;&gt;</a>
    <?php else: ?>
  <?php endif ?> 
</div>

Thank you kindly for any and all assistance.

By daniel - July 18, 2022

Hi Codee,

In general, the simplest way to do this is to add the htmlencode() at each place a variable is being output on the page, e.g. places with "echo". Like this:

Results page '<?php echo htmlencode($blogMetaData['page']); ?>' not found, <a href="<?php echo htmlencode($blogMetaData['firstPageLink']); ?>">start over &gt;&gt;</a>.<br><br>

Note that by default htmlencode() will re-encode strings even if they're already encoded, which may cause issues in some cases. Double-encoding can be turned off with the 3rd function parameter, like this:

<?php echo htmlencode($string, null, false); ?>

(The 2nd parameter has to do with encoding "<br>", passing null will leave the default behavior)

Let me know if that helps, or if you have any specific issues/questions I can address!

Thanks,

Daniel
Technical Lead
interactivetools.com