How to build friendly Urls, such as Facebook and Twitter.

Asked

Viewed 592 times

3

I have a question, how can I build links like Facebook and Twitter? For example: http://facebook.com/nome-qualquer.

I know that the .htaccess treats the url in a certain way, but the question I’m bumping my head is how to load the content of the url http://fb.com/fulano-de-tal

I took everything after the last bar and made a query in SQL with fulano-de-tal and then the result is returned?

2 answers

2

In your HTACCESS you should set something like

RewriteEngine on
RewriteRule ^([a-z]+)$ profiles.php?name=$1

There in your file php profiles. you recover the parameter $name and searches the information in the database about that person who wants to display on that page

so your url would look something like

www.seusite.com/tchicotti

but in fact your site would be being accessed in this way:

www.seusite.com/profiles.php? name=tchicotti

1

Routes

What you’re trying to do is what we call today routes (Routes).

When you make use of some Framework, most of them already contain this functionality by default, making managing routes much easier.

Nothing stops you from creating one .htaccess and define your routes, but it is less friendly and can make maintenance difficult.

You can create on .htaccess a route for everything after the bar (site.com.br/) is directed to a specific file, and in that file you can do the treatment you want, either with a simple if or something more sophisticated.

Follow an example:

.htaccess

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

// tudo que cair em /usuarios/usuario-x => será redirecionado para usuarios.php
RewriteRule ^usuarios/(\d+)*$ ./usuarios.php?id=$1

// o mesmo acontece com essas \/
RewriteRule ^posts/(\d+)*$ ./usuarios.php?id=$1
RewriteRule ^comunidades/(\d+)*$ ./comunidades.php?id=$1

php users.

<?php
    // aqui você irá encontrar os dados e tratar da forma que desejar.
    print_r($_SERVER['REQUEST_URI'])
?>

See how the route system of some Frameworks works works:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.