Search code examples
phpmysqlquotesmariadbdouble-quotes

input field showing an URL with quotes


I have to store some Wikipedia URLs into a MariaDB database.

It happens that some URLs contain quotes, like this one:

https://en.wikipedia.org/wiki/%22Heroes%22

so I use urlencode() to store them as "en.wikipedia.org%2Fwiki%2F%22Heroes%22".

If I urldecode() the URL, to show it inside an <input type="text"> field without all the % (they scare unskilled users), the quotes break the input value.

I found this workaround to show the result in a more comfortable way:

$url = 'en.wikipedia.org%2Fwiki%2F%22Heroes%22'; // it comes in this way from the DB
$tmp = str_replace('%22','&quot;', $url);
$url_input = urldecode($tmp);
echo "<input type=\"text\" value=\"$url_input\" />";

The value of $url_input works smoothly as a <a href anchor, and the query coming from the form is then filtered with FILTER_SANITIZE_URL and urlencode() to store it in the DB.

Is there a better way to do this?


Solution

  • Just use htmlspecialchars() instead of str_replace()

    $url = 'en.wikipedia.org%2Fwiki%2F%22Heroes%22'; // it comes in this way from the DB
    //$tmp = str_replace('%22','&quot;', $url);
    $url_input = htmlspecialchars(urldecode($url));
    echo "<input type=\"text\" value=\"$url_input\" />";
    

    I think it will work better than this