How to rewrite a URL?

5

Hello, I want to rewrite a URL and I know it needs to be .htaccess .

I have this URL : www.nomedomeusite.com/visualizar?id=8

My page visualizar.php at the beginning of body takes this id and makes a query in my database to get the rest of the information, like this:

$id = $_GET['id'];
$sql = "SELECT 'nome-da-empresa', 'logo', 'descricao' FROM 'cadastro' WHERE 'id' = $id"

I would like to know how to rewrite my URL , so that it can be that way:

www.nomedomeusite.com/empresas/nome-da-empresa

I need a very detailed explanation of each term used and each variable used to do this, because I have no knowledge of the programming involved in .htaccess

    
asked by anonymous 22.03.2017 / 03:43

3 answers

2

Nicolas you can use the following rule in your .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
# informa que será aplicada uma condicao no arquivo solicitado 
RewriteCond %{REQUEST_FILENAME} !-f [OR] 
RewriteCond %{REQUEST_FILENAME} \.php$

#cria a condicao
RewriteRule ^empresa/([a-z0-9-]+)/?$ /visualizar.php?nome=$1 [L,NC]

</IfModule>

Already in your view.php file you will have to make some modifications, for example, change your search in the bank, instead of looking for the id you go search for the company name.

$id = $_GET['nome'];
$sql = "SELECT 'nome-da-empresa', 'logo', 'descricao' FROM 'cadastro' WHERE 'nome-da-empresa' = $id"
    
26.03.2017 / 04:50
2

For your case, the solution would be demonstrated here, but because you do not know exactly what the structure of your table is, I will rely on the details provided in the comments. Although this is using a different table, the example is very simple. The only problem you would have would be slug which is basically the title of the article, but with some arrangements, it has this , and this here .

config.php

<?php

// configuracao (nao importante)
$config = array(
    'mysql' => array(
        'host'=> 'localhost',
        'usr' => 'root',
        'pwd' => '',
        'db'  => 'nuwie'
    ),
    'site' => array(
        'nome' => 'Site sem Nome',
        'inicio' => 'http://127.0.0.1:8080' . dirname($_SERVER['SCRIPT_NAME'])
    )
);

// agilizar a busca dos valores da configuração (nao importante) 
function conf($nome){
    $p = preg_split('/[\s-@]/', $nome);
    global $config;
    foreach($config as $nome => $valor){
        if($nome === $p[0] && array_key_exists($p[1], $valor)){
            return $config[$nome][$p[1]];
        }
    }
    return false;
}



// conexao
$mysqli = new  mysqli(conf('mysql-host'), conf('mysql-usr'), conf('mysql-pwd'), conf('mysql-db'));

if($mysqli->errno){
    die('Erro ao conectar banco de dados');
}

// buscar todos os artigos
function buscarArtigos($tabela){
    global $mysqli;
    $resultados = array();
    if($stmt = $mysqli->query("SELECT id,titulo,seo_url FROM {$tabela}")){
        if($stmt->num_rows > 0){
            while($rs = $stmt->fetch_assoc()){
                array_push($resultados, $rs);
            }
            return $resultados;
        }
    }
    return false;
}

// buscar um artigo pela sua ID
function buscarArtigo($id, $tabela){
    global $mysqli;
    if($stmt = $mysqli->query("SELECT * FROM {$tabela} WHERE id = {$id}")){
        if($stmt->num_rows > 0){
            return $stmt->fetch_assoc();
        }
    }
    return false;
}

// reajustar os titulos para que se adequem a url
// retirada de: http://www.visualscope.com/seo-friendly-urls.html
function friendly_seo_string($vp_string){

    $vp_string = trim($vp_string);

    $vp_string = html_entity_decode($vp_string);

    $vp_string = strip_tags($vp_string);

    $vp_string = strtolower($vp_string);

    $vp_string = preg_replace('~[^ a-z0-9_.]~', ' ', $vp_string);

    $vp_string = preg_replace('~ ~', '-', $vp_string);

    $vp_string = preg_replace('~-+~', '-', $vp_string);

    return $vp_string;
}

This file here basically contains the only two functions you would need to make the idea work Search and search >, which is the most (not important) created in the heat of the moment since they were simple except for the last one that can be useful and is not my own. The friendly_seo_string function is only required when you want to create a new article, for example:

  • When you create a new article, in the database table for the titulo and conteudo fields you can respectively use the desired title and content, the same applies to the adicionado field, but to the field seo_url would have to be the return of this function passing the title used as argument friendly_seo_string (title_used_no_article) . Or if you prefer, you can always write your own function, so you can do the same thing.

.htaccess

RewriteEngine On
RewriteRule ^artigos/[0-9]\/(.*)$ ver_artigo.php?artigo=$0

For this example you would not need too much in the .htaccess file, only these two lines would suffice, or you could still check that the rewrite module is enabled before enabling it.

SQL table

CREATE TABLE 'artigos' (
  'id' int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  'titulo' varchar(60) NOT NULL,
  'conteudo' text NOT NULL,
  'seo_url' varchar(60) NOT NULL,
  'adicionado' datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

index.php

<?php

require_once 'config.php';

print "<a href=\"" .  conf('site-inicio') ."\"><h1>" . conf('site-nome') . "</h1></a>";

// - inicio do conteudo
if(($artigos = buscarArtigos('artigos')) != false){
    foreach($artigos as $artigo){
        print "<div id=\"artigo\">";
        print  "<a href=\"artigos/{$artigo['id']}/{$artigo['seo_url']}\" target=\"_blank\"><h4>{$artigo['titulo']}</h4></a>";
        print "</div>";
    }
} else {
    print "Nenhum artigo encontrado";
}
// - fim do conteudo

?>

The index.php file simply provides the titles and links of existing articles. Attention to link to the article:

print  "<a href=\"artigos/{$artigo['id']}/{$artigo['seo_url']}\" target=\"_blank\"><h4>{$artigo['titulo']}</h4></a>";

NA% of what you store, for articles, must precede url at the beginning of href .

ver_artigo.php

<?php

require_once 'config.php';

if(isset($_GET['artigo'])){
    $artigo_id = explode('/', $_GET['artigo']);

    if(($artigo = buscarArtigo($artigo_id[0], 'artigos')) != false){
        print "<div id=\"artigo\">";
        print "<h2>{$artigo['titulo']}</h2>";
        print $artigo['conteudo'];
        print "</div>";
    } else {
        print "Artigo não encontrado";
    }

    print "<p><a href=\"" .  conf('site-inicio') ."\">voltar</a></p>";

} else {
    print "<h1>Erro</h1>";
}

?>

This part, would be the equivalent of your page visual.pph . Search the details of this article using your artigos and return them, if you can not find the article, provide a message that you could not find the article.

In this case, your id would be in this format similar to ptSO:

  

www.nomedomeusite.com/artigos/id/title-of-article

For the format:

  

www.nomedomeusite.com/companies/any-company

The url itself should be matched instead of slug on the page that shows the details of the selected item.

  

ps: I worked on the idea, but I did not give a damn about the security factor, so I recommend first of all that you search mainly about .htaccess , and of course, you can always adapt or even , improve the code so that it works more closely with what you want. If there are still any questions, leave them in the comments, and good luck.

Recommended Reading

Apache

25.03.2017 / 20:56
1

What you are looking for is a Front controller .

For such a solution in PHP you need something a little more elaborate, I recommend using a framework like symfony or derivatives. If you insist on doing it yourself.

The .htaccess to redirect the content to your view.php keeping your URI as / . but that's just part of it.

#.htaccess
<IfModule mod_rewrite.c>
 RewriteEngine On
 #Sua front controller
 DirectoryIndex visualizar.php
 # Desabilita MultiViews,assim quando "/visualizar"
 #   ele vai resolver internamente para "/visualizar.php/visualizar".
 <IfModule mod_negotiation.c>
    Options -MultiViews
 </IfModule>
<IfModule mod_rewrite.c>
    RewriteEngine On


    # Define um header HTTP_AUTHORIZATION, o apache se encarrega disso.
    RewriteCond %{HTTP:Authorization} .
    RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    #redirecionamento inicial caso tente entrar /visualizar.php joga para /.
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^visualizar\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]

    # Se existir o arquivo ele permanece disponivel.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]

    # Redireciona o restante para a front controller.
    RewriteRule ^ %{ENV:BASE}/visualizar.php [L]
</IfModule>

#saida para quando o mod_rewrite não esta disponivel
<IfModule !mod_rewrite.c>
    <IfModule mod_alias.c>
        RedirectMatch 302 ^/$ /visualizar.php/
    </IfModule>
</IfModule>

In PHP you can get the URI with $uri = $_SERVER['REQUEST_URI'];

If your system has lots of routes, I suggest using a ready library like the FastRoute from Nikki . has a post explaining it in more detail in the repository.

Now for the dynamic routes, the ones that you look for in the bank. if the access is large and / or the query very expensive for your system. Create a cache. but there would be something much more specific, where would you recommend using a framwork

    
22.03.2017 / 05:02