PATH_INFO does not show "extra" bars

Asked

Viewed 39 times

0

I’m using the $_SERVER["PATH_INFO"] to pass values to the backend through the url, not in the format ?chave=valor, instead, /:valor/ (identify the colon and return a variable with that name), however, when I have a request for the url //valor/ the value of $_SERVER["PATH_INFO"] is /valor/, causing some problems...

Why? And how to solve?

1 answer

0


I solved the problem using $_SERVER["SCRIPT_NAME"] and $_SERVER["REQUEST_URI"]:

//Requisição para example.com/index.php/foo//bar/baz
$current_route = str_replace("/", "\/", $_SERVER["SCRIPT_NAME"]); // \/index.php"
$current_route = preg_replace("/(\.[a-z]*)/", "($1)?", $current_route); // \/index(.php)?
$current_route = preg_replace("/{$current_route}/", "", $_SERVER["REQUEST_URI"]); // /foo//bar/baz

The second line makes extension optional .php because I hid the same by .htaccess

  • Do not use preg_replace thus {$current_route}, use preg_quote, or better, in this case you wouldn’t even need to.

  • @Guilhermenascimento I supplemented the answer, perhaps it was clearer, but if you think you’re wrong anyway, could you explain it to me? What’s wrong with {$current_route}?

  • The problem is to mix string with regular expression, but in general the last preg_replace could be replaced by substr counting the characters of $current_route, pq ai wouldn’t even need to preg_quote to prevent the URL from breaking the regex. The way this code of yours will just break if someone types in a URL like /[a-z]/ manually.

  • @Guilhermenascimento tested with [a-z] and even with .* in the middle of the URL and kept working, I don’t think you can use the substr this time because of the extension .php optional

  • Already left warned, mixing regex with string can be a problem, to avoid simply use preg_quote to escape metacharacters, the substr suggestion was to simplify, but preg_replace and preg_quote even if it gets more code already solves the whole problem.

  • @Guilhermenascimento how would you look? I tried here, unsuccessfully

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.