php - Have user query www.example.com/parameter and use that parameter without changing URL in url bar

760

So basically I have a website with user profiles. I want users to be able to query a profile like this: www.example.com/john

and that would trigger another page I've written in PHP to display that profile but WITHOUT then changing the url. I've looked at other examples on SO like this: How do I achieve a url like www.example.com/username to redirect to www.example.com/user/profile.php?uid=10?

However this uses url rewriting which means the URL would then change. For instnace if the page is called users.php, I don't want this to happen: user queries www.examples.com/john -> page is changed to www.examples.com/users.php?name=John

I want the url to stay as www.examples.com/john but for the server to serve up the page www.examples.com/users.php?name=John

Would I still use url rewriting to achieve this even though I don't want the url to change in the url bar? Hope someone can help, thank you!

654

Answer

Solution:

Usually who needs this kind of feature uses Routers.

Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request.

Basically you can take your url and divide it in parameters. The response it's related to the input url. There are some good libraries in php which allows you to handle routers, for example:

In phroute you can solve your problem just with:

$router->get(['/user/{name}', 'username'], function($name){
    //retrieve $name information
    return 'Hello ' . $name;
})

Just for information, every MVC framework uses router as standard.

375

Answer

Solution:

Using .htaccess File

RewriteEngine on
RewriteRule ^/([a-zA-Z0-9])$ /users.php?name=$1

I hope this will solve your issue, now what it will do, on the front or to the public url is likehttp://www.example.com/john butusers.php script on your server will receive a GET parameter name which will have the value john.

Just make sure apache mod_rewrite is turned on.

People are also looking for solutions to the problem: php - Get room for each user in chat room application considering users access level

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.