3

I have the function:

function after_char($char, $var) {
    $get = explode($char, $var);
    $text= $get[1];
    echo $text;
}

I have the html link:

<a href="http://<?php after_char('@', urlencode($post_email)); ?>" target="_blank">Potwierdź aktywację konta w <?php after_char('@', htmlspecialchars($post_email, ENT_QUOTES)); ?>.</a> 

How should be variables in both started functions encoded? Do I really need to write second the same function? First for urlencode, second for htmlspecialchars and encode it inside the function build and not within started function?

1 Answers1

0

You have reversed the order of operations. It is better to first prepare your data in your function, return it, then encode it for a particular context and echo out.

Use rawurlencode() to encode the URL which will go into href=.
Use htmlspecialchars to encode any other text displayed in HTML context.

Example:

<?php

function after_char($char, $var): string {
    $get  = explode($char, $var, 2);
    return $get[1]; // returns the part after the $char
}

$result_of_after_char = after_char('@', $post_email);
?>
<a href="http://<?= urlencode($result_of_after_char); ?>" target="_blank"
    >Potwierdź aktywację konta w <?= htmlspecialchars($result_of_after_char , ENT_QUOTES); ?>.</a>

On a side note the function after_char does not do anything more than the explode() does anyway. You could get rid of that function altogether:

$result_of_after_char = explode('@', $post_email, 2)[1];
Dharman
  • 30,962
  • 25
  • 85
  • 135