Search code examples
phpfriendly-urldynamic-url

have different static url in dynamic page


I have a website where each person has his personal profile. I would like to have static URL like mywebsite/user1, mywebsite/user2, but actually I would remain in the same page and change the content dynamically. A reason is that when I open the site I ask to a database some data, and I don't want to ask it each time I change page. I don't like url like mywebsite?user=1

Is there a solution?

Thank you

[EDIT better explenation]

I have a dynamic page that shows the user profile of my website. So the URL is something like http://mywebsite.me?user=2 but i would like to have a static link, like http://mywebsite.me/user2name

Why I want this? Because it's easy to remember and write, and because i can change dynamically the content of the page, without asking each time data to my database (i need some shared info in all the pages. info are the same for all the pages)


Solution

  • Yes there are solutions to your problem!

    The first solution is server dependend. I am a little unsure how this works on an IIS server but it's quiet simple in Apache. Apache can take directives from a file called .htaccess. The .htaccess file needs to be in the same folder as your active script to work. It also needs the directive AllowOverride All and the module mod_rewrite loaded in the main server configuration. If you have all this set up you need to edit your .htaccess file to contain the following

    RewriteEngine on
    RewriteRule ^mywebsite/([^/\.]+)/?$ index.php?user=$1 [L]
    

    This will allow you to access mywebsite/index.php?user=12 with mywebsite/12. A beginner guide to mod_rewrite.

    You could also fake this with only PHP. It will not be as pretty as the previous example but it is doable. Also, take into concideration that you are working with user input so the data is to be concidered tainted. The user needs to access the script via mywebsite/index.php/user/12.

    <?php
        $request = $_SERVER['REQUEST_URI'];
        $request = explode($request, '/'); // $request[0] will contain the name of the .php file
        $user[$request[1]] = $request[2];
    
        /* Do stuff with $user['user'] */
    ?>
    

    These are the quickest way I know to acheive what you want.