Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Encoding forward slashes in PHP

i have a page in PHP where i'm trying to connect to an API and get information on motorcycles, the problem here is that i use an internal route to call the API via CURL and this route is accessible as follows

http://mywebpage.dev/manufacturer/BETA/year/2016/category/M/model/MINI%20CROSS%2010%2F10/versions

I encode this and then i try to send it through to the API where it gets decoded and the JSON response sent back, however the problem is that for some reason it's not even getting to the route's method whenever i have any forward slashes, regardless of me encoding them or not...

I'm really running out of options here, what exactly is the problem here? Shouldn't URI Encoding fix these sorts of issues? Why is PHP still treating %2F as if it were a forward slash? And is there any way to make this work?

EDIT

In my javascript i'm getting the text for the Model via jQuery and encoding it as follows

var model    = $(".model-list li.active").text();
model = encodeURI(model);

Then i have a laravel route that takes in the encoded string from the Javascript call and returns it to a PHP function

public function versionsByYear($manufacturer, $year, $category, $model)
{
    $manufacturer = str_replace(" ", "%20", $manufacturer);
    $model        = str_replace(" ", "%20", $model);

    return $this->connect('manufacturer/'.$manufacturer.'/year/'.$year.'/category/'.$category.'/model/'.$model.'/versions');
}

Which in turn links to another one that makes a CURL request to the external API

public function connect($method)
{

    $url    = $this->apiUrl . '/' . $method;

    $ch     = curl_init();

    curl_setopt_array($ch, array(
        CURLOPT_URL             => $url,
        CURLOPT_HTTPHEADER      => array('Token: ' . $this->token),
        CURLOPT_RETURNTRANSFER  => true
    ));

    $out = curl_exec($ch);

    curl_close($ch);

    return $out;

}

The API itself is not the problem as it works when i pass it the exact same encoded model names that fail on my application. the Application simply returns an empty string, having failed to find the method defined in the route completely, possibly due to interpreting the encoded %20 as a forward slash?

like image 853
João Serra Avatar asked Mar 24 '26 09:03

João Serra


1 Answers

The encoded slashes are probably decoded as normal path separators by your webserver before they are passed to PHP. For example, Apache has a specific setting to allow these: AllowEncodedSlashes On.

You can use this to keep Apache from parsing the encoded slashes.

<VirtualHost 127.0.0.1:80>
  ServerName site.example.com
  AllowEncodedSlashes On
  # ...
</VirtualHost>
like image 160
Johan Avatar answered Mar 26 '26 23:03

Johan