Passing variables through the URL using friendly URL via GET

Asked

Viewed 83,787 times

11

I am trying to mess with friendly URL. Before, to pass the variables I used for example:

pagina.php?variavel=valordavariavel

by clicking on this link I could use a echo and display the variable. I am now trying to use the user friendly URL so technically there is no more pagina.php?variavel=valordavariavel.

Be alone:

pagina/valordavarivel

However, I cannot turn this value into a PHP variable to display it. How do I do this?

5 answers

15


I wrote the code below to show something more "sophisticated", as the challenge proposes.

The first point that caught my attention was the following excerpt in the AP question

by clicking on this link I could use an echo and display the variable. Now I’m trying to use the user friendly URL so technically there is no plus the.php page? variavel=valuables.

This may not be the case for AP, but we should be aware that even a URL in the URL-friendly format (Rewrite URL), should allow access by normal mode.

Many systems mistakenly build their Urls by ignoring the normal way of mounting URL parameters. This is a problem because it does not allow the system to be used in environments that do not have a user-friendly URL feature.

From this script below, we highlight different points of most "solutions" to rescue parameters.

1. Subfolder support and relative URL basis

The "REQUEST_URI" key of the global variable $_SERVER, returns the entire query of a URL. This may be a problem if the script runs inside a subfolder. It can also be a problem if the file name is explicitly invoked in the URL.

Example: http://localhost/pasta/parametro1/parametro2

$_SERVER['REQUEST_URI'] will return /pasta/parametro1/parametro2.

If we do not identify the basis of the relative URL, we will have a conflict in the parameters.

The script below does this check and also checks the existence of the script file name, for the cases of Fake friendly URL.

Example: http://localhost/pasta/index.php/parametro1/parametro2

$_SERVER['REQUEST_URI'] will return /pasta/index.php/parametro1/parametro2.

2. Normal URL, user-friendly URL, false friendly URL and Command line support (cli).

In the HTTP protocol, the standard and normal format of parameters in a URL is the traditional format using the parameter argument.

The parameter argumentator is represented by the question symbol (?).

Example: http://localhost/?p=foo/bar

We call this "normal URL".

In the user-friendly URL, also known as "URL rewriting", "rewrite URL" or "sugary URL", the parameters and the argumentator are omitted.

Example: http://localhost/foo/bar

For this to work, the environment web server must have URL rewriting support. The most popular web server is Apache. In this example, we will only talk about your use with Apache.

The fake friendly URL is a kind of gambiarra that allows you to create user-friendly Urls without using URL rewriting features like Apache’s mod_rewrite.

This technique arose due to market demand to use user-friendly URL on hosting servers without URL rewriting support.

Example: http://localhost/index.php/foo/bar

The command line, also known as CLI or CLI SAPI, in PHP, is an ignored or poorly supported execution medium for most applications. Usually the most popular frameworks on the market offer all the features described here, including command line executions.

Example: /caminho/do/compildor/php -f /caminho/do/script/index.php foo/bar

In the script below, there is support for command line interface (shell prompt).

For the command line, the parameters follow the same format as a friendly URL because the end result of any of the means of execution will be the same.

3. Friendly URL support by the POST method

It is recommended not to mix different request methods into a single request.

Example:

<form action="pagina.php?foo=bar" method="POST">
<input type="submit" name="test" value="ok" />
</form>

The "action" parameter of the tag form has parameters in the format GET. However, the method defined is "POST". To rescue this data on.php page, it will be necessary to invoke $_GET to obtain the value of "foo" and $_POST to get the value of "test"

Technically there are no serious problems like data conflict or anything like that. The problem in this is organization and also difficulty in implementing a way to rescue such data in a flexible and dynamic way.

In order to uncomplicate, it is recommended to adopt a data sending pattern by a single method.

In the case of sending data via the POST method, a user-friendly URL makes no sense because the parameters are not visible in the URL as in the GET method.

Therefore, it is recommended not to use a user-friendly URL for sending data using the POST method.

However, we must adapt to the demands of the market. Like the use of fake friendly URL, the script below also provides a means to allow URL friendly by the POST method. In this case, the friendly URL address is ignored and only the parameters sent by the POST method are extracted.

Magic Quotes!

It is a native PHP feature that, when enabled, adds escape characters to the values of the received parameters.

This feature was discontinued in PHP 5.3.0 and removed completely in version 5.4.0. http://php.net/manual/en/security.magicquotes.php

Currently many hosting servers have an environment with PHP 5.3 or even lower versions like 5.1 or 4 with Magic Quotes activated.

The script below has this check as a backward compatibility feature, allowing it to run on older versions of PHP.

<?php
date_default_timezone_set('Asia/Tokyo');

ini_set('error_reporting', E_ALL);
ini_set('log_errors',TRUE);
ini_set('html_errors',FALSE);
ini_set('display_errors',TRUE);

define('CHARSET', 'UTF-8');

ini_set('default_charset', CHARSET);

if (PHP_VERSION < 5.6)
{
    ini_set('mbstring.http_output', CHARSET);
    ini_set('mbstring.internal_encoding', CHARSET);
}


/**
Caminho base da URL relativa.
Exemplo, caso execute esse script sob um subolder: http://localhost/pasta/index.php
O valor de $path_base deve ser "/pasta/" ($path_base = '/pasta/';)
Caso execute na raíz do endereço, apenas defina com uma barra "/" ($path_base = '/';)
*/
$path_base = '/';

/**
Nome deste arquivo que executa os scripts.
*/
$index_file_name = basename($_SERVER['SCRIPT_FILENAME']);

/**
Verifica se está sendo executado por interface de linha de comando.
Caso a constante PHP_SAPI retorne a string "cli", retorna "true". Caso contrário, "false".
*/
$cli_mode = (strtolower(PHP_SAPI) == 'cli'? true : false);

/**
Caso $cli_mode for falso, resgatamos os parâmetros da chave "REQUEST_URI".
Caso $cli_mode for true, os parâmetros serão resgatados da chave "argv".
*/
$uri = (!$cli_mode? $_SERVER['REQUEST_URI'] : (isset($_SERVER['argv'][1])? $_SERVER['argv'][1] : ''));

/**
Remove o caminho base do parâmetro resgatado de $_SERVER['REQUEST_URI'] ou $_SERVER['argv'].
*/
if (!empty($uri))
{
    $len = mb_strlen($path_base.$index_file_name);

    if ($path_base.$index_file_name == substr($uri, 0, $len))
        $uri = substr($uri, $len);

    $len = mb_strlen($path_base);

    if ($path_base == substr($uri, 0, $len))
        $uri = substr($uri, $len);
}

/**
Caso não esteja sob interface de linha de comando (cli), executa os processos dentro da condicional.
*/
if (!$cli_mode)
{
    /**
    Resgata o método da requisição caso não esteja sob interface de linha de comando (cli).
    */
    $method = (isset($_SERVER['REQUEST_METHOD'])? strtoupper($_SERVER['REQUEST_METHOD']) : null);

    /**
    true: Permite URL amigável pelo método POST.
    false: Nega URL amigável pelo método POST.

    Recomendável manter como false.
    */
    $allow_mode_rewrite_by_post = false;

    /**
    Verifica se os parâmetros possuem formato normal ou formato de URL reescrita.
    */
    if (substr($uri, 0, 1) == '?')
        $mode_rewrite = false;
    else{
        if ($method == 'POST')
        {
            $mode_rewrite = ($allow_mode_rewrite_by_post? true : false);
        }else{
            $mode_rewrite = true;
        }
    }

    /**
    A query parece provir de uma URL normal.
    */
    if (!$mode_rewrite)
    {

        /**
        Nome do parâmetro padrão para recebimento de nomes de rotas.
        Exemplo: http://localhost/?p=foo/bar
        */
        $route_parameter = 'p';

        /**
        Nessa condição, resgatamos um parâmetro padrão que contém a rota.
        O nome do parâmetro é definido na variável $route_parameter.
        */
        $uri = (isset($GLOBALS['_'.$method][$route_parameter]) ? $GLOBALS['_'.$method][$route_parameter] : null);

        /**
        Suporte para servidores com magic_quotes ativado.
        */
        if (!empty($uri) && get_magic_quotes_gpc())
            $uri = stripslashes($uri);
    }
}


/**
Exemplos de uso

URL normal: http://localhost/index.php?p=foo/bar ou http://localhost/?p=foo/bar
URL amigável falsa: http://localhost/index.php/foo/bar
URL amigável: http://localhost/foo/bar
Linha de comando: /caminho/do/compildor/php -f /caminho/do/script/index.php foo/bar

Para URL amigável sob o módulo Rewrite Module do Apache, o arquivo .htaccess deve conter o seguinte código:

DirectoryIndex index.php

RewriteEngine on
RewriteBase /

Options FollowSymLinks

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

RewriteRule (.+) /


*/

/**
Configura o ccharset no cabeçalho.
*/
header('Content-Type: text/html; charset='.CHARSET);

/**
Imprime "URI: foo/bar"
O output será sempre a parte relevante da URI. 
Exemplo: localhost/foo/bar, localhost/?p=foo/bar e os outros meios, retornam "foo/bar"
*/
echo 'URI: '.$uri;

SEO, HTML link rel="Change"

For SEO purposes, it is important to be concerned about the URL information. If the system allows access to different URL formats, it is recommended to define link rel="alternate" pointing to the "official URL".

This prevents search engines, such as google bot, from penalizing the page as a duplicate of some other previously indexed page.

In a practical example, we have the following URL http://localhost/foo/bar which can also be accessed as http://localhost/?p=foo/bar.

If the search bot has access to the normal URL, the system must identify that the request does not come from the default URL and add the HTML header to the tag <link> whose attribute rel is set to "Alternate". For the attribute href, set the default (official) URL where the bot should actually go and ignore penalties. Example:

<link rel="alternate" href="http://localhost/foo/bar" hreflang="en" />
  • Would it be possible to apply this solution in wordpress? I’m using variables in the URL this way localhost/wp/?layout=2 how to make this? localhost/wp/layout/2

11

.HTACCESS

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} \.php$
RewriteRule (.*) index.php [QSA,L]


ROUTE

// www.site.com/carros/novos -> carros/novos
$url = ltrim( parse_url( $_SERVER['REQUEST_URI'] , PHP_URL_PATH ) , '/' );

$rotas = explode( '/' , $url );
$rotas[0] // carros
$rotas[1] // novos


Next step is to get the information from the URL, it depends on your system.
You can use explode or PREG with your defined routes.

It’s a pretty superficial example of URL routing

5

In this example I will cite I am using only one parameter.

Normal URL:

http://www.site.com.br/pagina.php?conteudo=criativo

URL friendly:

http://www.site.com.br/pagina?conteudo=criativo

First, separate the contents before and after the equal sign:

$separaigual  = explode("=", $_SERVER["REQUEST_URI"]);

Now that we’ve passed the URL to a array we have both strings down below:

$separaigual['0'];  // ficou:  /pagina?conteudo
$separaigual['1'];  // ficou:  criativo

Note that in this example we can perfectly catch the parameter criativo of the variable conteudo.
But, and to get the variable conteudo?

To get the variable name conteudo, we must separate the before and after the question mark:

$separainterrogacao = explode("?", $ separaigual['0']);

Now we have a array with both strings:

$separainterrogacao ['0'];  // ficou:  /pagina
$separainterrogacao ['1'];  // ficou: conteudo

So now we have the $separainterrogacao ['1'] being the variable conteudo and the $separaigual['1'] being the parameter criativo.

For an example of selecting a post in a database via SQL would have:

"SELECT * FROM tabela WHERE nomedopost = '$separaigual[1]'"

And a probation check if for example we could do so:

If($separainterrogacao ['1'] === "criativo"):
   echo "mostre o conteúdo";
else:
   echo "Não mostre o conteudo";
endif; 

It may not be the best way, but it’s a practical way I found.

2

The answers above are excellent solutions, but I’m going to ask you a very simple question, why don’t you use a framework? Everyone already solves their problem by default. In addition to professional growth and maturation, with modern frameworks you will be learning good practices and new php standards, I recommend the following:

Beginner:

  • Codeigniter

Middleman:

  • Laravel
  • Cakephp
  • Yii

Advanced:

  • Symfony
  • Zend

If you want to be a professional, I highly recommend the use of a framework, for learning, later you can even create your own.

  • Don’t forget about Drupal!

  • 1

    I posted in particular the ones I know and I’ve had contact with, but as far as I can remember, Drupal is CMS not?!

  • It’s true, I got confused

  • 1

    Hi, I am the Devil’s Advocate and my client does not want to use a Framework because: first he wants to learn how things work; knowing this it is easier to operate and manipulate a Framework; and after all, much easier to create his own Flamework ;) But obviously, it can all be done the other way around, as you propose..!

  • I advise the study of the language, the new practices of modern php and a good read on the PSR http://www.php-fig.org/ and also a read on the concepts OOP and MVC. Learning a framework directly really limits the general/complete knowledge of the language, but it is also a quicker way to learn all concepts in general, gets the choice of the person. My humble opinion.

2

I could not make it work using only the permissions of rewritten. To even work I also had to add to the code this stretch of character debug on the listing page of links. I used for a news system where I had highlights that led to the open page, see:

Debug

<?php
//URL DEBUG CHARACTERS
function encodeSEOString($string) {
    $string = preg_replace("`\[.*\]`U", "", $string);
    $string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i', '-', $string);
    $string = htmlentities($string, ENT_COMPAT, 'utf-8');
    $string = preg_replace("`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i", "\\1", $string);
    $string = preg_replace(array("`[^a-z0-9]`i", "`[-]+`"), "-", $string);
    return strtolower(trim($string, '-'));
}

?>

Link

<a href='/noticia/".encodeSEOString{$read['titulo']}.".'>ABRIR NOTICIA</a>

.htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
RewriteRule ^noticia\/?([0-9]+)\/?(.+)\/?$ noticia.php?titulo=$1

Download

https://drive.google.com/file/d/0B7k9YhCyYGeST216aGNBVVoydEU/view?usp=sharing

Browser other questions tagged

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