Às vezes, é preciso pegar a url atual para usar em alguma variável ou condicional. Veja como é simples, basta usarmos uma função para puxar esta informação.

function UrlAtual(){
 $dominio= $_SERVER['HTTP_HOST'];
 $url = "http://" . $dominio. $_SERVER['REQUEST_URI'];
 return $url;
 }

Depois, basta usar como preferir, por exemplo, se quiser apenas imprimir o resultado na tela:

echo "A URL atual é: ". UrlAtual();

Simples. 🙂

Atualização (20/09/2017) via Stack Exchange

$url ="http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

Para suportar https:

$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

16 Comments to “Pegando a url atual com PHP”

    1. Para o caso que precisei, eu tinha que armazenar a url atual e compará-la com outras. Como precisava usar em outras partes do meu código, criei uma função.

      Mas para um uso único, o código que você fez é excelente.

      Reply
  1. Markus Luan

    Amigo, queria saber se tendo duas paginas, index.php com um form e recebe.php que recebe esse form, eu teria como pegar a url da index.php através da recebe.php? Pois preciso fazer a verificação de quem está direcionando para a minha página.

    Reply
  2. Valmir

    Teria como pegar só parte?
    Queria pegar só o nome da pagina que tá na Url. Tipo: “exemplo.php”.

    Reply
  3. Jeff

    Por favor pode falar sobre a insegurança de usar o
    $_SERVER[‘HTTP_HOST’];
    Já li um texto mas era em inglês e não me lembro onde foi

    Grato !

    Reply
  4. Elísio Sekualáli da Conceição Décimo

    Bom dia pessoal
    Penso que poderia ser assim_

    $documentophp = str_replace( $_SERVER[‘REQUEST_URI’], ” , $_SERVER[‘PHP_SELF’] );
    echo $documentophp;

    Se der certo no seu teste dê um retorno…

    Reply
  5. It came a moment when I realized I might not need a plumber after all.
    For a long time the water in my apartment was flowing badly — unstable water supply, and the water heater was heating poorly — lukewarm water.
    I contacted several plumbers, but everyone said different things.
    Some blamed the filters, others suggested replacing everything.
    Money was spent, time was wasted, and the problem was still there.
    At some point I decided to understand the issue myself and started looking for clear explanations, not guesses.
    That’s how I came across practical construction and plumbing articles here:
    https://stroyka2001.kh.ua
    The site explains hidden reasons for poor water pressure in a simple, structured way — without unnecessary theory or advertising.
    After reading a few materials, I finally understood what had been overlooked.
    With this knowledge, I discussed everything with a plumber — and together we fixed the issue properly, without extra replacements.
    Very useful resource if you want to understand household problems better.

    Reply

Post Comment