How to use a global variable for a link

Asked

Viewed 211 times

1

I’m trying to use $_SERVER['DOCUMENT_ROOT'] to facilitate the use of links where you could call the variable in any directory of the site. To use with the include($pagina_inicial) works, but for link does not work:

For example:

<?php
$pagina_inicial = $_SERVER['DOCUMENT_ROOT'] . '/index.php';
?>
<a href="<?php $pagina_inicial ?>">Link</a>
// Seria o equivalente disso:
<a href="www.site.com/index.php">Link</a>
// Mas está retornando assim: 
// http://www.site.com/home/u711323471/public_html/index.php

Does anyone know how I can do that??

  • 2

    The best is to use relational paths. For example / is root. So you can do only $pagina_inicial = '/index.php'; and another board: $pagina_inicial = '/outra_dir/index.php';

  • What Sergio said, but here’s a useful snippet to inspect variables: printf( '<pre><code>%s</code></pre>', print_r( $_SERVER, true ) );

  • The answer is, don’t use it that way.. The reason is it doesn’t make sense because it’s a global variable and virtually constant. Follow @Sergio’s advice

  • I will use it this way. Thanks Sergio and cia for the help.

2 answers

2


With suggest before, it is best to use related paths.

For example / is root. So you can do only $pagina_inicial = '/index.php'; and another board: $pagina_inicial = '/outra_dir/index.php';

Or don’t use php variables and do:

<a href="/index.php">Link</a> // se o ficheiro estiver na root
<a href="/../index.php">Link</a> // se o ficheiro estiver numa descendente direta da root

1

You could use the HTTP_HOSTor the SERVER_NAME, I believe they will pass the variable the way you want it.

If you have any questions, PHP Manual has a function-only page $_SERVER, take a look here.

Browser other questions tagged

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