How can I do in php to detect the id of a user in a link for example:
facebook.com/092439542392435555
and return on the page the details about that account
How can I do in php to detect the id of a user in a link for example:
facebook.com/092439542392435555
and return on the page the details about that account
If you are not using routing in php, I would reccomend you use “get” requests in the url. For example, instead of:
example.com/id/283493248923489234
You would want to use:
example.com/id?id=283493248923489234
To “capture” the value of id in php, you would want to use the $_GET
variable. If you have a page called id.php
and it contains this code:
<?php
echo $_GET["id"];
Somebody who visits /id.php?id=123 would see 123
on their screen.
One way you can handle requests like that is using a .htaccess
file with a RewriteRule
.
The exact rewrite route depends on how you are going to set up your routes. However the most basic would propably be:
RewriteRule ^(.*)$ index.php?url=$1 [L, QSA]
The first part, ^(.*)$
, is a regex that is being matched against the request path.
The second part, index.php?url=$1
, is where the request will be redirected to. The $1
is the result of the first (and in this case, only) capturing group. The result of a second capturing group would be called $2
, and so on.
The last part, [L, QSA]
, is a list of flags. L
indicates that it is the last applicable rule, and QSL
indicates that any query string should be appended to the new path. E.g. domain.com/123?key=value
would become domain.com/index.php?url=123&key=value
.
The above will redirect all requests to your index.php file. You will then be able to access the url
query parameter using:
$url = $_GET['url']
// you can then use if / switch to process different url values
If you know that the id will only contain numbers, and you want a seperate file to handle the request, you can use the following:
RewriteRule ^([0-9]+)$ user.php?id=$1 [L, QSA]
This will redirect requests like domain.com/1234
to user.php, but will leave other requests unchanged (e.g. domain.com/abcd
). In this case you would use $_GET['id']
to get the id number.
Just note that this assumes you are using the Apache web server; this will not work if you are not using the lamp-poc project on glitch.