Okt 01
Sometimes, you might need to check whether a string has already been urlencoded with PHP or not. Sadly, PHP doesn't offer such a function but because I recently needed it, I tried this one:
/** * Returns true if given string is url encoded * * @param string $string * @return boolean */ function is_urlencoded($string) { return $string === urlencode(urldecode($string)); }
This works fine for me (as far as I have tested), so maybe it is a litte help for anyone with the same problem

















It does not work:
Check out this example:
$string = ‘/wiki/%C3%89lections_l%C3%A9gislatives_irakiennes_de_2010′;
# I know for sure it is urlencoded
echo is_urlencoded($string) ? urldecode($string) : $string;
Though, the idea is great, I think it should be:
function is_urlencoded($string) {
return $string !== urlencode(urldecode($string));
}
Actually it is easier than that:
function is_urlencoded($string) {
return urldecode($string) != $string;
}
should be ok.
Hi justme.
At first your given string is NOT urlencoded, because it had to start with %2F otherwise, because “/” is “%2F” after urlencode(“/”)!
Second, you can easily check which function works on which string and which does not. Here a simple phpunit testcase:
< ?php
require_once 'PHPUnit/Framework.php';
class TestIsUrlEncoded extends PHPUnit_Framework_TestCase {
public function testMyFunction() {
$this->assertTrue(is_urlencoded(‘%2Fwiki%2F%C3%89lections_l%C3%A9gislatives_irakiennes_de_2010′));
$this->assertFalse(is_urlencoded(‘/wiki/%C3%89lections_l%C3%A9gislatives_irakiennes_de_2010′));
}
public function testShortFunction() {
$this->assertTrue(is_urlencoded_short(‘%2Fwiki%2F%C3%89lections_l%C3%A9gislatives_irakiennes_de_2010′));
$this->assertFalse(is_urlencoded_short(‘/wiki/%C3%89lections_l%C3%A9gislatives_irakiennes_de_2010′));
}
public function testWrongFunction() {
$this->assertTrue(is_urlencoded_wrong(‘%2Fwiki%2F%C3%89lections_l%C3%A9gislatives_irakiennes_de_2010′));
$this->assertFalse(is_urlencoded_wrong(‘/wiki/%C3%89lections_l%C3%A9gislatives_irakiennes_de_2010′));
}
}
function is_urlencoded($string) {
return $string === urlencode(urldecode($string));
}
function is_urlencoded_short($string) {
return urldecode($string) != $string;
}
function is_urlencoded_wrong($string) {
return $string !== urlencode(urldecode($string));
}
?>
You can easily adjust the testcase to your needs. Hope that helps.