Search code examples
phpprepared-statementurlencodeurldecode

Prepared statements for building a URL in PHP


When building a URL, you can use urldecode and urlencode to escape specific strings, but I'm trying to build strings of the form:

$url = "/myobject/id=$id/property=$property"

and so on. I have quite a number of these "URL building" statements in my application, and I don't want to have to remember to put urlencode around every single variable in each URL.

In PHP (and other languages) you can safely build a SQL query using a prepared statement. For example:

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

The purpose here is to escape any nasty characters in $firstname, $lastname or $email.

I'm wondering if there is a way to do something similar. The code I'm looking for is something like:

$url = safe_build_url("/myobject/id=?/property=?", $id, $property)

I could use printf to build strings like this, but they aren't escaped property. I could also use urlencode on the whole $url variable, but that loses slashes I want to keep.


Solution

  • PHP has http_build_query() for that:

    $data = array('foo'=>'bar',
                  'baz'=>'boom',
                  'php'=>'hypertext processor');
    
    echo http_build_query($data); // foo=bar&baz=boom&php=hypertext+processor
    

    Using the $encType param you can even choose the type of urlencoding to be used. If you want it in the same way as urlencode() then select PHP_QUERY_RFC3986 for the $enctype. (It is not the default).