How to get current url with PHP

Asked

Viewed 52,823 times

3

I have this link below.

http://example.com/Novo/adm/categoria/1-Nome_Categoria

http://example.com/Novo/adm.php?categoria=1

However I will need to compare current URL, to make a menu activation scheme.

Below the code displaying this result above.

<?php 
    $URL_ATUAL= "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    echo $URL_ATUAL;
?>

For need to make this comparison I just need to get the URL below.

adm/categoria/1-Nome_Categoria

I tried to use the explode but did not return the correct URL.

  • It wouldn’t just be the value of $_SERVER["REQUEST_URI"]?

  • You’re just returning me. Novo/adm/categoria/1-Nome_Categoria Adm forward.

  • You have to cut the URI

  • All the URL’s that you pick up have Adm in front ? or always want to cut the first path ?

  • URI is returning the correct path, however, I would like to remove from the string this New

3 answers

4


As stated in the comments, the content of the global variable $_SERVER["REQUEST_URI"] is the way:

Novo/adm/categoria/1-Nome_Categoria

It was also stated in the comments that the content of interest is only the part of adm from then on, just treat this value by removing that which is not of interest. This can be done in various ways.

If the directory name is not changed over time, just removing the contents of the string is enough:

$url = str_replace("Novo/", "", $_SERVER["REQUEST_URI"]);

In this way, $url would be adm/categoria/1-Nome_Categoria, as desired.

If the directory name is subject to change over time, but there is always a directory, you can only remove the first snippet of the string until the first occurrence of /:

$url = substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], '/')+1);

The result will be the same, regardless of what the directory name is, as long as there is a.

If there is a possibility that there is more than one directory, but that the URL will always start with adm, you can search for this snippet in your URL, this way:

$url = substr($_SERVER["REQUEST_URI"], strpos($_SERVER["REQUEST_URI"], 'adm'));

The result would also be the same, regardless of the number and name of directories present in the URL.

  • Excellent tutorial friend, I added a / at first and really worked the way it was supposed to work. $url = str_replace("/Novo/", "", $_SERVER["REQUEST_URI"]);

  • Look I’d like to know the following: http://example.com/Novo/adm/categoria/1-Nome_Categoria http://example.com/Novo/adm.php?categoria=1-Nome_Categoria I wonder if I can verify if this category comes (Numeric) and if I can display type like this. http://example.com/Novo/adm/categoria/1-Nome_Categoria http://example.com/Novo/adm.php?categoria=1

  • Display where? If this question is very different from the current one, it might be interesting to create a new one to discuss this.

1

I have a very nice class for this task, feel free to use it, opinion, study, etc...

This would be the form of use of the same:

<?php $uri = URI::base(); echo $uri; ?>

or only...

<?php echo URI::base(); ?>

https://github.com/webrafael/Projetos/tree/master/pegar-url-principal-php

Below the structure of the class

<?php
class URI {

/**
 * $protocolo
 * @var string | $protocolo
 * @access private
 */
static private $protocolo;
/**
 * $host
 * @var string | $host
 * @access private
 */
static private $host;
/**
 * $scriptName
 * @var string | $scriptName
 * @access private
 */
static private $scriptName;
/**
 * $finalBase
 * @var string | $finalBase
 * @access private
 */
static private $finalBase;

/**
 * protected function Protocolo()
 * ----------------------------------------------
 *            Obtém o protocolo da url
 * ----------------------------------------------
 * @return string | Ex: http://... - https://...
 * @access protected
 */
protected function Protocolo()
{
    /**
     * Faz a verificação se for
     * diferente de https
     */
    if(strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === false)
    {
        self::$protocolo = 'http://'; //Atribui o valor http
    }
    else
    {
        self::$protocolo = 'https://'; //Atribui o valor https
    }
    /**
     * Retorna o protocolo em formato string
     * @var string
     */
    return self::$protocolo;
}
/**
 * protected function Host()
 * ----------------------------------------------
 *            Obtém o host principal
 * ----------------------------------------------
 * @return string | Ex: www.example.com.br
 * @access protected
 */
protected function Host()
{
    self::$host = $_SERVER['HTTP_HOST']; //Atribui o valor www.example.com.br
    /**
     * Retorna o host em formato string
     * @var string
     */
    return self::$host;
}
/**
 * protected function scriptName()
 * ----------------------------------------------
 * Obtém o script name do host após a primeira barra
 * ----------------------------------------------
 * @return string | Ex: .../dir/index.php
 * @access protected
 */
protected function scriptName()
{
    /**
     * $scr
     * Atribui o valor do SCRIPT_NAME em uma
     * variável $scr e utiliza-se a função dirname()
     * para remover qualquer nome de arquivo .html, .php, etc...
     * @var string
     */
    $scr = dirname($_SERVER['SCRIPT_NAME']);
    /**
     * Faz a contagem de barras que contém a url principal
     * o objetivo aqui é pegar o nível de pasta onde hospeda-se o diretório
     * caso ele exista.
     */
    if(!empty($scr) || substr_count($scr, '/') > 1)
    {
        self::$scriptName = $scr . '/'; //atribui o valor do diretório com uma "/" na sequência
    }
    else
    {
        self::$scriptName = ''; //atribui um valor vazio
    }
    /**
     * Retorna o scriptName em formato string
     * @var string
     */
    return self::$scriptName;
}
/**
 * public function base()
 * ----------------------------------------------
 *          Monta a url base e retorna
 * ----------------------------------------------
 * @return [type] [description]
 * @access public
 */
public function base()
{
    //Concatena os valores
    self::$finalBase = self::Protocolo() . self::Host() . self::scriptName();
    /**
     * Retorna toda a url construida em formato string
     * @var string
     */
    return self::$finalBase;
}
}
?>
  • All right, I put the fullest possible answer to be more objective.

1

can use

<?php
echo $_SERVER['SCRIPT_URI'];
?>

or the short form

<?=$_SERVER['SCRIPT_URI']?>

Browser other questions tagged

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