Encoding and Decoding a Query String

Ever had to pass a url parameter with special characters and then your application has trouble decoding it back? Or maybe you need to pass this parameter to a shell script, I've encountered this situation with the PHP Photo Gallery, sometimes some galleries would contain ampersands, single quotes or double quotes, so I created two simple functions to handle this in the gallery.

Test Link with Text containing special characters.

Decoded String:
Encoded String:



strings.php

<?php
/**
 * Encoding and decoding strings with special characters in the query string.
 * 
 * @author Herbert Balagtas
 *
 */ 
 
$str = '';
if ( isset($_GET['str']) ){
	$str = $_GET['str'];
} else {
	$str = "æ±å­ ~ æ±å­ Pancake's & Cookies Good Old fashioned waffles.";
}
/*if ( isset($_GET['str']) ){
	$str = decode_string($_GET['str']);
} else {
	$str = "æ±å­ ~ æ±å­ Pancake's & Cookies Good Old fashioned waffles.";
}

$url = encode_string($str);*/

echo '<a href="?str='.encode_string($str).'">Test Link with Text containing special characters.</a>';

if (isset($_GET['str'])){
	echo '<br />';
	echo '<br />';
	echo 'Decoded String using the decode_string function: ';
	echo '<br />';
	echo decode_string($_GET['str']);
}


function encode_string($str){
	$str = htmlentities($str, ENT_QUOTES);
	$str = urlencode($str);
	return $str;
}

function decode_string($str){
	$str = html_entity_decode($str, ENT_QUOTES);
	$str = stripslashes(urldecode($str));
	return $str;
}
?>
<br />
<br />
<form action="" method="get">
Decoded String: <input type="text" name="str" value="<?php echo decode_string($str);?>" style="width: 500px;"/>
<br />
Encoded String: <input type="text" name="decoded" value="<?php echo encode_string($str);?>" style="width: 500px;"/>
<input type="submit" value="Submit" />
</form>

Personal Links

Favorite Links