Redeem id passed by URL without using GET

0

I have a question that I think is simple for almost everyone, but I did not find any material that really helped me solve it.

I am developing a micro-service in php that has as sole objective to re-use a set of functions in php that I got from another application.

So far so good, but one of the main functions of this set makes a check of the current url, being in a format similar to "... / users / {userid}" to use that userid for a certain processing.

The question is: how do I, when I type something like "... / users / 15" in the browser, it redirects me to this function file and throws the value 15 where it is "{userid } "?

Edit 1: I was able to resolve using the friendly url method in the response marked as appropriate, thanks to everyone.

    
asked by anonymous 26.04.2018 / 03:56

2 answers

2

I'm not very good at REGEX.

If your url is like this: "www.site.com.br/algo/seila/tantofaz/{15}"

You can do this:

$string = $_SERVER["REQUEST_URI"]; // pega a url
preg_match_all ('/\{\d*\}/', $string, $matches) ; // pega o valor que está {15}
$valor = str_replace(array("{", "}"), "", $matches[0][0]); // pega apenas o numero
echo $valor; // imprime

With the value, you can do whatever you want in your functions.

You could also work this way:

"www.site.com.br/users/index.php/{15}"

Using the file in the users directory.

How do I, when I type something like "... / users / 15" in the browser, it redirects me to this function file and throws the value 15 where it is "{userid}"

Using an example with explode() suggested by @Bacco would be:

Url: www.site.com/users/index.php/15

include("../diretorioDasFuncoes/arquivoFuncoes.php");  // inclui o arquivo que contém as funções
$string = $_SERVER["REQUEST_URI"]; // pega essa string "/users/index.php/15"
$urlParts = explode("/", $string); // transforma em array
$userid = $urlParts[3]; // recupera o valor
funcaoUser($userid); // usa a função necessária

/*

$urlParts <-- array("", "users", "index.php", 15)

  /users/index.php/15

^    ^       ^      ^
.    .       .      ....... [3]
.    .       .............. [2]
.    ...................... [1]
........................... [0]

*/
    
26.04.2018 / 04:27
1

Get the explode and select the part of the numbers.

Then you make a regex or a function that captures only the string numbers stored in the variable.

It would look something like this:

$url_desejada =" https://www.url.com.br/?id=0909090908";
$numeros=explode('/' , $url_desejada);
$imprime =$numeros[3];

function números($imprime)
{

    return 

      preg_replace("/[^0-9]/", "", $imprime);
}

Simplifying:

$url_desejada =" https://www.url.com.br/?id=0909090908";
$numeros=explode('/' , $url_desejada);

$ id = preg_replace ("/ [^ 0-9] /", "", $ numbers);

echo $ numbers [3];

Good luck!

:)

    
25.11.2018 / 10:07