Encoding html entities in url string
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 $titleentencod开发者_JAVA技巧ed; ?></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?
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.
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.
精彩评论