Search code examples
javascriptphpurl-encoding

reading a url in PHP that has been encoded in javascript


In Javascript i encode parts of the request parameter like this

window.location.href = "search.php?qry=" + encodeURIComponent("m & l");

In my Search.php i reach this like this

$url = urldecode($_SERVER['REQUEST_URI']);
echo ."Full URL: " .$url ."<br>";
$parts = parse_url($url);
parse_str($parts['query'], $query);
$qry = "Just Query: " .trim($query['qry']);
echo $qry ."<br>";

This prints out:

Full Url: /Search.php?qry=m & l
Just Query: m

Looks like the stuff after the & is being dropped in the 'm & l`

What changes do i need to make in PHP or Javascript?


Solution

  • Just change:

    $url = urldecode($_SERVER['REQUEST_URI']);
    

    to

    $url = $_SERVER['REQUEST_URI'];
    

    You're basically double-decoding as parse_url will decode it as well.

    Worth noting that PHP has already done this for you so there's not really a reason to parse your own URL. $_GET['qry'] will contain 'm & l'

    If you're doing this for several query variables, you'll need to run encodeURIComponent separately for each.

    Example:

    window.location.href = "search.php?qry=" + encodeURIComponent("m & l") + "&subcat="+encodeURIComponent("hello & there");
    

    You're explicitly telling it to encode the & after all.