I am using PHP header redirect to redirect users from account/?id=$id
to user/$username
Successfully it takes for instance account/?id=1
to user/samuel
as long as the user exists. Now, this page user/samuel
is quite empty ( 404 ).
How do I make it return the user data in the user/samuel
using something like isset($_GET[])
manual? in addition of course to adding MYSQL query to retrieve data for the user which has username extracted from the URL, and get their data from database table. and I will be placing all the code in user/index.php
As long as I could make account/?id=$id
get the $id
from URL ( parameter ) and do other db stuff I think it is also possible to get $username from the URL.. even though user/?username
could do it but I don't want to include an ?
in the URL..
Any thoughts?
It might be better if you use Url Rewriting (aka friendly urls)
You can see this link which answers this same question, although your case is a little bit different. Apache friendly urls
Since you can't convert $id to $username (both are different values) I would recommend to change the link to 'user/ID' instead of 'user/USERNAME'.
This is a pretty broad topic, what you need to do is parse the url - IE break it into parts and then match the url to a set of actions. This is commonly known as routing.
A naive implementation would be a:
$parts = explode($_SERVER['REQUEST_URI'], '/');
if ( $parts[-2] === 'user' && $parts[-1] ) {
$stmt = $pdo->prepare("SELECT * FROM 'users' WHERE username = ? OR id = ?");
$result = $stmt->execute(array($parts[-1], array($parts[-1]));
// ... do something if the user is found or not.
}
But this would fail if the url contains query parameters (?foo=bar
) or a hash (#foo
).
Instead you can use parse_url
to make sure you only use the path.
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = null;
// Match the url with a regular expression.
preg_match(/^\/user\/(\w*)$/, $path, $parts);
if ( count($parts) == 2 ) {
$stmt = $pdo->prepare("SELECT * FROM 'users' WHERE username = ? OR id = ?");
$result = $stmt->execute(array($parts[-1], array($parts[-1]));
// ... do something if the user is found or not.
}
But in the end you might want consider using a micro framework such as Silex, Slim or using the Routing component from Symfony2 so that you can concentrate on building your application rather than reinventing the wheel.