2

I'm trying to prepare a url that has special characters in it, to be used as GET variables in a php file. I think I need html entities and urlencode, which I then need to decode in the other php file. But I'm running into some problems with correctly encoding them. This is what I have:

<?php $title = "This is a ‘simple’ test"; ?>
<?php $titleent = htmlentities($title); ?>
<?php $titleentencoded = urlencode($titleent); ?>
<?php $date = '21-12-2011'; ?>

    <p>Title: <?php echo $title; ?></p>
    <p>Title html entities: <?php echo $titleent; ?></p>
    <p>Title encoded: <?php echo $titleencoded; ?></p>

    <p><a href="index.php?title=<?php echo $titleencoded; ?>&date=<?php echo $date; ?>">Go!</a></p>

The $titleencoded variable turns out to be empty. I'm overlooking something obvious but I can't see it. What am I doing wrong?


EDIT: New code after suggestions

Okay, so here's what I came up with:

<?php $title = "This is a ‘simple’ test"; ?>
<?php $titleentencoded = urlencode($title); ?>
<?php $htmlent = htmlentities($titleentencoded); ?> 
<?php $date = '21-12-2011'; ?>

<p>Title: <?php echo $title; ?></p>
<p>Title encoded: <?php echo $titleentencoded; ?></p>
<p>Title html entities: <?php echo $htmlent; ?></p>

<p><a href="index.php?title=<?php echo $htmlent; ?>&date=<?php echo $date; ?>">Go!</a></p>

Is this the right way?

2
  • Don't use htmlentities(). Use htmlspecialchars() instead. What you're using will convert ALL characters to HTML entities (which is NOT what you want). Commented Sep 27, 2011 at 14:25
  • Please see the edit to the original code. Is this the right way? Commented Sep 27, 2011 at 16:47

2 Answers 2

4

Your variable is empty because you have a typo. You initialize $titleentencoded but later use $titleencoded:

<?php $titleentencoded = urlencode($titleent); ?>

// Should be
<?php $titleencoded = urlencode($titleent); ?>

See @Quentin's answer for a logic error.

Sign up to request clarification or add additional context in comments.

3 Comments

Typos...the bane of every programmer's existence.
Thanks... And yes, typos, hate them with the power of a 1000 suns. Sucks my brain's responsible for them ;)
Use JS, Python, Java or any modern language, and it will at least warn you and not silently fail :)
4

You are doing it backwards.

You are putting data in a URL, then a URL in an HTML document.

You need to urlencode the data, put it in the URL then htmlencode the URL and put it in the document.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.